CGCreature.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691
  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 "../texts/CGeneralTextHandler.h"
  14. #include "../CConfigHandler.h"
  15. #include "../IGameSettings.h"
  16. #include "../callback/IGameInfoCallback.h"
  17. #include "../callback/IGameEventCallback.h"
  18. #include "../callback/IGameRandomizer.h"
  19. #include "../gameState/CGameState.h"
  20. #include "../mapObjectConstructors/CObjectClassesHandler.h"
  21. #include "../networkPacks/PacksForClient.h"
  22. #include "../networkPacks/PacksForClientBattle.h"
  23. #include "../networkPacks/StackLocation.h"
  24. #include "../serializer/JsonSerializeFormat.h"
  25. #include "../entities/faction/CTownHandler.h"
  26. #include <vstd/RNG.h>
  27. VCMI_LIB_NAMESPACE_BEGIN
  28. std::string CGCreature::getHoverText(PlayerColor player) const
  29. {
  30. if(stacks.empty())
  31. {
  32. //should not happen...
  33. logGlobal->error("Invalid stack at tile %s: subID=%d; id=%d", anchorPos().toString(), getCreature(), id.getNum());
  34. return "INVALID_STACK";
  35. }
  36. MetaString ms;
  37. CCreature::CreatureQuantityId monsterQuantityId = stacks.begin()->second->getQuantityID();
  38. int quantityTextIndex = 172 + 3 * (int)monsterQuantityId;
  39. if(settings["gameTweaks"]["numericCreaturesQuantities"].Bool())
  40. ms.appendRawString(CCreature::getQuantityRangeStringForId(monsterQuantityId));
  41. else
  42. ms.appendLocalString(EMetaText::ARRAY_TXT, quantityTextIndex);
  43. ms.appendRawString(" ");
  44. ms.appendNamePlural(getCreatureID());
  45. return ms.toString();
  46. }
  47. std::string CGCreature::getHoverText(const CGHeroInstance * hero) const
  48. {
  49. if(hero->hasVisions(this, BonusCustomSubtype::visionsMonsters))
  50. {
  51. MetaString ms;
  52. ms.appendNumber(stacks.begin()->second->getCount());
  53. ms.appendRawString(" ");
  54. ms.appendName(getCreatureID(), stacks.begin()->second->getCount());
  55. return ms.toString();
  56. }
  57. else
  58. {
  59. return getHoverText(hero->tempOwner);
  60. }
  61. }
  62. std::string CGCreature::getMonsterLevelText() const
  63. {
  64. std::string monsterLevel = LIBRARY->generaltexth->translate("vcmi.adventureMap.monsterLevel");
  65. bool isRanged = getCreature()->getBonusBearer()->hasBonusOfType(BonusType::SHOOTER);
  66. std::string attackTypeKey = isRanged ? "vcmi.adventureMap.monsterRangedType" : "vcmi.adventureMap.monsterMeleeType";
  67. std::string attackType = LIBRARY->generaltexth->translate(attackTypeKey);
  68. boost::replace_first(monsterLevel, "%TOWN", getCreature()->getFactionID().toEntity(LIBRARY)->getNameTranslated());
  69. boost::replace_first(monsterLevel, "%LEVEL", std::to_string(getCreature()->getLevel()));
  70. boost::replace_first(monsterLevel, "%ATTACK_TYPE", attackType);
  71. return monsterLevel;
  72. }
  73. std::string CGCreature::getPopupText(const CGHeroInstance * hero) const
  74. {
  75. std::string hoverName;
  76. if(hero->hasVisions(this, BonusCustomSubtype::visionsMonsters))
  77. {
  78. MetaString ms;
  79. ms.appendRawString(getHoverText(hero));
  80. ms.appendRawString("\n\n");
  81. int decision = takenAction(hero, true);
  82. switch (decision)
  83. {
  84. case FIGHT:
  85. ms.appendLocalString(EMetaText::GENERAL_TXT,246);
  86. break;
  87. case FLEE:
  88. ms.appendLocalString(EMetaText::GENERAL_TXT,245);
  89. break;
  90. case JOIN_FOR_FREE:
  91. ms.appendLocalString(EMetaText::GENERAL_TXT,243);
  92. break;
  93. default: //decision = cost in gold
  94. ms.appendLocalString(EMetaText::GENERAL_TXT,244);
  95. ms.replaceNumber(decision);
  96. break;
  97. }
  98. hoverName = ms.toString();
  99. }
  100. else
  101. {
  102. hoverName = getHoverText(hero->tempOwner);
  103. }
  104. if (settings["general"]["enableUiEnhancements"].Bool())
  105. {
  106. hoverName += getMonsterLevelText();
  107. hoverName += LIBRARY->generaltexth->translate("vcmi.adventureMap.monsterThreat.title");
  108. int choice;
  109. uint64_t armyStrength = getArmyStrength();
  110. uint64_t heroStrength = hero->getTotalStrength();
  111. double ratio = static_cast<double>(armyStrength) / heroStrength;
  112. if (ratio < 0.1) choice = 0;
  113. else if (ratio < 0.25) choice = 1;
  114. else if (ratio < 0.6) choice = 2;
  115. else if (ratio < 0.9) choice = 3;
  116. else if (ratio < 1.1) choice = 4;
  117. else if (ratio < 1.3) choice = 5;
  118. else if (ratio < 1.8) choice = 6;
  119. else if (ratio < 2.5) choice = 7;
  120. else if (ratio < 4) choice = 8;
  121. else if (ratio < 8) choice = 9;
  122. else if (ratio < 20) choice = 10;
  123. else choice = 11;
  124. hoverName += LIBRARY->generaltexth->translate("vcmi.adventureMap.monsterThreat.levels." + std::to_string(choice));
  125. }
  126. return hoverName;
  127. }
  128. std::string CGCreature::getPopupText(PlayerColor player) const
  129. {
  130. std::string hoverName = getHoverText(player);
  131. if (settings["general"]["enableUiEnhancements"].Bool())
  132. hoverName += getMonsterLevelText();
  133. return hoverName;
  134. }
  135. std::vector<Component> CGCreature::getPopupComponents(PlayerColor player) const
  136. {
  137. return {
  138. Component(ComponentType::CREATURE, getCreatureID())
  139. };
  140. }
  141. void CGCreature::onHeroVisit(IGameEventCallback & gameEvents, const CGHeroInstance * h) const
  142. {
  143. //show message
  144. if(!message.empty())
  145. {
  146. InfoWindow iw;
  147. iw.player = h->tempOwner;
  148. iw.text = message;
  149. iw.type = EInfoWindowMode::MODAL;
  150. gameEvents.showInfoDialog(&iw);
  151. }
  152. int action = takenAction(h);
  153. switch( action ) //decide what we do...
  154. {
  155. case FIGHT:
  156. fight(gameEvents, h);
  157. break;
  158. case FLEE:
  159. {
  160. flee(gameEvents, h);
  161. break;
  162. }
  163. case JOIN_FOR_FREE: //join for free
  164. {
  165. BlockingDialog ynd(true,false);
  166. ynd.player = h->tempOwner;
  167. ynd.text.appendLocalString(EMetaText::ADVOB_TXT, 86);
  168. ynd.text.replaceName(getCreatureID(), getJoiningAmount());
  169. gameEvents.showBlockingDialog(this, &ynd);
  170. break;
  171. }
  172. default: //join for gold
  173. {
  174. assert(action > 0);
  175. //ask if player agrees to pay gold
  176. BlockingDialog ynd(true,false);
  177. ynd.player = h->tempOwner;
  178. ynd.components.emplace_back(ComponentType::RESOURCE, GameResID(GameResID::GOLD), action);
  179. std::string tmp = LIBRARY->generaltexth->advobtxt[90];
  180. boost::algorithm::replace_first(tmp, "%d", std::to_string(getJoiningAmount()));
  181. boost::algorithm::replace_first(tmp, "%d", std::to_string(action));
  182. boost::algorithm::replace_first(tmp,"%s",getCreature()->getNamePluralTranslated());
  183. ynd.text.appendRawString(tmp);
  184. gameEvents.showBlockingDialog(this, &ynd);
  185. break;
  186. }
  187. }
  188. }
  189. CreatureID CGCreature::getCreatureID() const
  190. {
  191. return CreatureID(getObjTypeIndex().getNum());
  192. }
  193. const CCreature * CGCreature::getCreature() const
  194. {
  195. return getCreatureID().toCreature();
  196. }
  197. TQuantity CGCreature::getJoiningAmount() const
  198. {
  199. return std::max(static_cast<int64_t>(1), getStackCount(SlotID(0)) * cb->getSettings().getInteger(EGameSettings::CREATURES_JOINING_PERCENTAGE) / 100);
  200. }
  201. void CGCreature::pickRandomObject(IGameRandomizer & gameRandomizer)
  202. {
  203. switch(ID.toEnum())
  204. {
  205. case MapObjectID::RANDOM_MONSTER:
  206. subID = gameRandomizer.rollCreature();
  207. break;
  208. case MapObjectID::RANDOM_MONSTER_L1:
  209. subID = gameRandomizer.rollCreature(1);
  210. break;
  211. case MapObjectID::RANDOM_MONSTER_L2:
  212. subID = gameRandomizer.rollCreature(2);
  213. break;
  214. case MapObjectID::RANDOM_MONSTER_L3:
  215. subID = gameRandomizer.rollCreature(3);
  216. break;
  217. case MapObjectID::RANDOM_MONSTER_L4:
  218. subID = gameRandomizer.rollCreature(4);
  219. break;
  220. case MapObjectID::RANDOM_MONSTER_L5:
  221. subID = gameRandomizer.rollCreature(5);
  222. break;
  223. case MapObjectID::RANDOM_MONSTER_L6:
  224. subID = gameRandomizer.rollCreature(6);
  225. break;
  226. case MapObjectID::RANDOM_MONSTER_L7:
  227. subID = gameRandomizer.rollCreature(7);
  228. break;
  229. }
  230. try {
  231. // sanity check
  232. LIBRARY->objtypeh->getHandlerFor(MapObjectID::MONSTER, subID);
  233. }
  234. catch (const std::out_of_range & )
  235. {
  236. // Try to generate some debug information if sanity check failed
  237. CreatureID creatureID(subID.getNum());
  238. throw std::out_of_range("Failed to find handler for creature " + std::to_string(creatureID.getNum()) + ", identifier:" + creatureID.toEntity(LIBRARY)->getJsonKey());
  239. }
  240. ID = MapObjectID::MONSTER;
  241. setType(ID, subID);
  242. }
  243. void CGCreature::initObj(IGameRandomizer & gameRandomizer)
  244. {
  245. blockVisit = true;
  246. switch(character)
  247. {
  248. case 0:
  249. character = -4;
  250. break;
  251. case 1:
  252. character = gameRandomizer.getDefault().nextInt(1, 7);
  253. break;
  254. case 2:
  255. character = gameRandomizer.getDefault().nextInt(1, 10);
  256. break;
  257. case 3:
  258. character = gameRandomizer.getDefault().nextInt(4, 10);
  259. break;
  260. case 4:
  261. character = 10;
  262. break;
  263. }
  264. stacks[SlotID(0)]->setType(getCreature());
  265. const Creature * c = getCreature();
  266. if(stacks[SlotID(0)]->getCount() == 0)
  267. {
  268. stacks[SlotID(0)]->setCount(gameRandomizer.getDefault().nextInt(c->getAdvMapAmountMin(), c->getAdvMapAmountMax()));
  269. if(stacks[SlotID(0)]->getCount() == 0) //armies with 0 creatures are illegal
  270. {
  271. logGlobal->warn("Stack cannot have 0 creatures. Check properties of %s", c->getJsonKey());
  272. stacks[SlotID(0)]->setCount(1);
  273. }
  274. }
  275. temppower = stacks[SlotID(0)]->getCount() * static_cast<int64_t>(1000);
  276. refusedJoining = false;
  277. }
  278. void CGCreature::newTurn(IGameEventCallback & gameEvents, IGameRandomizer & gameRandomizer) const
  279. {//Works only for stacks of single type of size up to 2 millions
  280. if (!notGrowingTeam)
  281. {
  282. if (stacks.begin()->second->getCount() < cb->getSettings().getInteger(EGameSettings::CREATURES_WEEKLY_GROWTH_CAP) && cb->getDate(Date::DAY_OF_WEEK) == 1 && cb->getDate(Date::DAY) > 1)
  283. {
  284. ui32 power = static_cast<ui32>(temppower * (100 + cb->getSettings().getInteger(EGameSettings::CREATURES_WEEKLY_GROWTH_PERCENT)) / 100);
  285. gameEvents.setObjPropertyValue(id, ObjProperty::MONSTER_COUNT, std::min<uint32_t>(power / 1000, cb->getSettings().getInteger(EGameSettings::CREATURES_WEEKLY_GROWTH_CAP))); //set new amount
  286. gameEvents.setObjPropertyValue(id, ObjProperty::MONSTER_POWER, power); //increase temppower
  287. }
  288. }
  289. if (cb->getSettings().getBoolean(EGameSettings::MODULE_STACK_EXPERIENCE))
  290. gameEvents.setObjPropertyValue(id, ObjProperty::MONSTER_EXP, cb->getSettings().getInteger(EGameSettings::CREATURES_DAILY_STACK_EXPERIENCE)); //for testing purpose
  291. }
  292. void CGCreature::setPropertyDer(ObjProperty what, ObjPropertyID identifier)
  293. {
  294. switch (what)
  295. {
  296. case ObjProperty::MONSTER_COUNT:
  297. stacks[SlotID(0)]->setCount(identifier.getNum());
  298. break;
  299. case ObjProperty::MONSTER_POWER:
  300. temppower = identifier.getNum();
  301. break;
  302. case ObjProperty::MONSTER_EXP:
  303. giveAverageStackExperience(identifier.getNum());
  304. break;
  305. case ObjProperty::MONSTER_REFUSED_JOIN:
  306. refusedJoining = identifier.getNum();
  307. break;
  308. }
  309. }
  310. int CGCreature::takenAction(const CGHeroInstance *h, bool allowJoin) const
  311. {
  312. //calculate relative strength of hero and creatures armies
  313. double relStrength = static_cast<double>(h->getValueForDiplomacy()) / getArmyStrength();
  314. int powerFactor;
  315. if(relStrength >= 7)
  316. powerFactor = 11;
  317. else if(relStrength >= 1)
  318. powerFactor = static_cast<int>(2 * (relStrength - 1));
  319. else if(relStrength >= 0.5)
  320. powerFactor = -1;
  321. else if(relStrength >= 0.333)
  322. powerFactor = -2;
  323. else
  324. powerFactor = -3;
  325. int count = 0; //how many creatures of similar kind has hero
  326. int totalCount = 0;
  327. for(const auto & elem : h->Slots())
  328. {
  329. bool isOurUpgrade = vstd::contains(getCreature()->upgrades, elem.second->getCreatureID());
  330. bool isOurDowngrade = vstd::contains(elem.second->getCreature()->upgrades, getCreatureID());
  331. if(isOurUpgrade || isOurDowngrade)
  332. count += elem.second->getCount();
  333. totalCount += elem.second->getCount();
  334. }
  335. int sympathy = 0; // 0 if hero have no similar creatures
  336. if(count)
  337. sympathy++; // 1 - if hero have at least 1 similar creature
  338. if(count*2 > totalCount)
  339. sympathy++; // 2 - hero have similar creatures more that 50%
  340. int diplomacy = h->valOfBonuses(BonusType::WANDERING_CREATURES_JOIN_BONUS);
  341. int charisma = powerFactor + diplomacy + sympathy;
  342. if(charisma < character)
  343. return FIGHT;
  344. if (allowJoin && cb->getSettings().getInteger(EGameSettings::CREATURES_JOINING_PERCENTAGE) > 0)
  345. {
  346. if((cb->getSettings().getBoolean(EGameSettings::CREATURES_ALLOW_JOINING_FOR_FREE) || character == Character::COMPLIANT) && diplomacy + sympathy + 1 >= character)
  347. return JOIN_FOR_FREE;
  348. if(diplomacy * 2 + sympathy + 1 >= character)
  349. {
  350. int32_t recruitCost = getCreature()->getRecruitCost(EGameResID::GOLD);
  351. int32_t stackCount = getStackCount(SlotID(0));
  352. return recruitCost * stackCount; //join for gold
  353. }
  354. }
  355. //we are still here - creatures have not joined hero, flee or fight
  356. if (charisma > character && !neverFlees)
  357. return FLEE;
  358. else
  359. return FIGHT;
  360. }
  361. void CGCreature::fleeDecision(IGameEventCallback & gameEvents, const CGHeroInstance *h, ui32 pursue) const
  362. {
  363. if(refusedJoining)
  364. gameEvents.setObjPropertyValue(id, ObjProperty::MONSTER_REFUSED_JOIN, false);
  365. if(pursue)
  366. {
  367. fight(gameEvents, h);
  368. }
  369. else
  370. {
  371. gameEvents.removeObject(this, h->getOwner());
  372. }
  373. }
  374. void CGCreature::joinDecision(IGameEventCallback & gameEvents, const CGHeroInstance *h, int cost, ui32 accept) const
  375. {
  376. if(!accept)
  377. {
  378. if(takenAction(h,false) == FLEE)
  379. {
  380. gameEvents.setObjPropertyValue(id, ObjProperty::MONSTER_REFUSED_JOIN, true);
  381. flee(gameEvents, h);
  382. }
  383. else //they fight
  384. {
  385. h->showInfoDialog(gameEvents, 87, 0, EInfoWindowMode::MODAL);//Insulted by your refusal of their offer, the monsters attack!
  386. fight(gameEvents, h);
  387. }
  388. }
  389. else //accepted
  390. {
  391. if (cb->getResource(h->tempOwner, EGameResID::GOLD) < cost) //player don't have enough gold!
  392. {
  393. InfoWindow iw;
  394. iw.player = h->tempOwner;
  395. iw.text.appendLocalString(EMetaText::GENERAL_TXT,29); //You don't have enough gold
  396. gameEvents.showInfoDialog(&iw);
  397. //act as if player refused
  398. joinDecision(gameEvents, h, cost, false);
  399. return;
  400. }
  401. //take gold
  402. if(cost)
  403. gameEvents.giveResource(h->tempOwner,EGameResID::GOLD,-cost);
  404. giveReward(gameEvents, h);
  405. for(auto & stack : this->stacks)
  406. stack.second->setCount(getJoiningAmount());
  407. gameEvents.tryJoiningArmy(this, h, true, true);
  408. }
  409. }
  410. void CGCreature::fight(IGameEventCallback & gameEvents, const CGHeroInstance * h) const
  411. {
  412. //split stacks
  413. int stacksCount = getNumberOfStacks(h);
  414. //source: http://heroescommunity.com/viewthread.php3?TID=27539&PID=1266335#focus
  415. int amount = getStackCount(SlotID(0));
  416. int m = amount / stacksCount;
  417. int b = stacksCount * (m + 1) - amount;
  418. int a = stacksCount - b;
  419. SlotID sourceSlot = stacks.begin()->first;
  420. for (int slotID = 1; slotID < a; ++slotID)
  421. {
  422. int stackSize = m + 1;
  423. gameEvents.moveStack(StackLocation(id, sourceSlot), StackLocation(id, SlotID(slotID)), stackSize);
  424. }
  425. for (int slotID = a; slotID < stacksCount; ++slotID)
  426. {
  427. int stackSize = m;
  428. if (slotID) //don't do this when a = 0 -> stack is single
  429. gameEvents.moveStack(StackLocation(id, sourceSlot), StackLocation(id, SlotID(slotID)), stackSize);
  430. }
  431. if (stacksCount > 1)
  432. {
  433. if (containsUpgradedStack()) //upgrade
  434. {
  435. SlotID slotID = SlotID(static_cast<si32>(std::floor(static_cast<float>(stacks.size()) / 2.0f)));
  436. const auto & upgrades = getStack(slotID).getCreature()->upgrades;
  437. if(!upgrades.empty())
  438. {
  439. auto it = RandomGeneratorUtil::nextItem(upgrades, gameEvents.getRandomGenerator());
  440. gameEvents.changeStackType(StackLocation(id, slotID), it->toCreature());
  441. }
  442. }
  443. }
  444. gameEvents.startBattle(h, this);
  445. }
  446. void CGCreature::flee(IGameEventCallback & gameEvents, const CGHeroInstance * h) const
  447. {
  448. BlockingDialog ynd(true,false);
  449. ynd.player = h->tempOwner;
  450. ynd.text.appendLocalString(EMetaText::ADVOB_TXT,91);
  451. ynd.text.replaceName(getCreatureID(), getStackCount(SlotID(0)));
  452. gameEvents.showBlockingDialog(this, &ynd);
  453. }
  454. void CGCreature::battleFinished(IGameEventCallback & gameEvents, const CGHeroInstance *hero, const BattleResult &result) const
  455. {
  456. if(result.winner == BattleSide::ATTACKER)
  457. {
  458. giveReward(gameEvents, hero);
  459. gameEvents.removeObject(this, hero->getOwner());
  460. }
  461. else if(result.winner == BattleSide::NONE) // draw
  462. {
  463. // guarded reward is lost forever on draw
  464. gameEvents.removeObject(this, hero->getOwner());
  465. }
  466. else
  467. {
  468. //merge stacks into one
  469. TSlots::const_iterator i;
  470. const CCreature * cre = getCreature();
  471. for(i = stacks.begin(); i != stacks.end(); i++)
  472. {
  473. if(cre->isMyDirectUpgrade(i->second->getCreature()))
  474. {
  475. gameEvents.changeStackType(StackLocation(id, i->first), cre); //un-upgrade creatures
  476. }
  477. }
  478. //first stack has to be at slot 0 -> if original one got killed, move there first remaining stack
  479. if(!hasStackAtSlot(SlotID(0)))
  480. gameEvents.moveStack(StackLocation(id, stacks.begin()->first), StackLocation(id, SlotID(0)), stacks.begin()->second->getCount());
  481. while(stacks.size() > 1) //hopefully that's enough
  482. {
  483. // 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)
  484. i = stacks.end();
  485. i--;
  486. SlotID slot = getSlotFor(i->second->getCreature());
  487. if(slot == i->first) //no reason to move stack to its own slot
  488. break;
  489. else
  490. gameEvents.moveStack(StackLocation(id, i->first), StackLocation(id, slot), i->second->getCount());
  491. }
  492. gameEvents.setObjPropertyValue(id, ObjProperty::MONSTER_POWER, stacks.begin()->second->getCount() * 1000); //remember casualties
  493. }
  494. }
  495. void CGCreature::blockingDialogAnswered(IGameEventCallback & gameEvents, const CGHeroInstance *hero, int32_t answer) const
  496. {
  497. auto action = takenAction(hero);
  498. if(!refusedJoining && action >= JOIN_FOR_FREE) //higher means price
  499. joinDecision(gameEvents, hero, action, answer);
  500. else if(action != FIGHT)
  501. fleeDecision(gameEvents, hero, answer);
  502. else
  503. assert(0);
  504. }
  505. bool CGCreature::containsUpgradedStack() const
  506. {
  507. //source http://heroescommunity.com/viewthread.php3?TID=27539&PID=830557#focus
  508. float a = 2992.911117f;
  509. float b = 14174.264968f;
  510. float c = 5325.181015f;
  511. float d = 32788.727920f;
  512. int val = static_cast<int>(std::floor(a * visitablePos().x + b * visitablePos().y + c * visitablePos().z + d));
  513. return ((val % 32768) % 100) < 50;
  514. }
  515. int CGCreature::getNumberOfStacks(const CGHeroInstance *hero) const
  516. {
  517. //source http://heroescommunity.com/viewthread.php3?TID=27539&PID=1266094#focus
  518. double strengthRatio = static_cast<double>(hero->getArmyStrength()) / getArmyStrength();
  519. int split = 1;
  520. if (strengthRatio < 0.5f)
  521. split = 7;
  522. else if (strengthRatio < 0.67f)
  523. split = 6;
  524. else if (strengthRatio < 1)
  525. split = 5;
  526. else if (strengthRatio < 1.5f)
  527. split = 4;
  528. else if (strengthRatio < 2)
  529. split = 3;
  530. else
  531. split = 2;
  532. ui32 a = 1550811371u;
  533. ui32 b = 3359066809u;
  534. ui32 c = 1943276003u;
  535. ui32 d = 3174620878u;
  536. ui32 R1 = a * static_cast<ui32>(visitablePos().x) + b * static_cast<ui32>(visitablePos().y) + c * static_cast<ui32>(visitablePos().z) + d;
  537. ui32 R2 = (R1 >> 16) & 0x7fff;
  538. int R4 = R2 % 100 + 1;
  539. if (R4 <= 20)
  540. split -= 1;
  541. else if (R4 >= 80)
  542. split += 1;
  543. vstd::amin(split, getStack(SlotID(0)).getCount()); //can't divide into more stacks than creatures total
  544. vstd::amin(split, 7); //can't have more than 7 stacks
  545. return split;
  546. }
  547. void CGCreature::giveReward(IGameEventCallback & gameEvents, const CGHeroInstance * h) const
  548. {
  549. InfoWindow iw;
  550. iw.player = h->tempOwner;
  551. if(!resources.empty())
  552. {
  553. gameEvents.giveResources(h->tempOwner, resources);
  554. for(const auto & res : GameResID::ALL_RESOURCES())
  555. {
  556. if(resources[res] > 0)
  557. iw.components.emplace_back(ComponentType::RESOURCE, res, resources[res]);
  558. }
  559. }
  560. if(gainedArtifact != ArtifactID::NONE)
  561. {
  562. gameEvents.giveHeroNewArtifact(h, gainedArtifact, ArtifactPosition::FIRST_AVAILABLE);
  563. iw.components.emplace_back(ComponentType::ARTIFACT, gainedArtifact);
  564. }
  565. if(!iw.components.empty())
  566. {
  567. iw.type = EInfoWindowMode::AUTO;
  568. iw.text.appendLocalString(EMetaText::ADVOB_TXT, 183); // % has found treasure
  569. iw.text.replaceRawString(h->getNameTranslated());
  570. gameEvents.showInfoDialog(&iw);
  571. }
  572. }
  573. static const std::vector<std::string> CHARACTER_JSON =
  574. {
  575. "compliant", "friendly", "aggressive", "hostile", "savage"
  576. };
  577. void CGCreature::serializeJsonOptions(JsonSerializeFormat & handler)
  578. {
  579. handler.serializeEnum("character", character, CHARACTER_JSON);
  580. if(handler.saving)
  581. {
  582. if(hasStackAtSlot(SlotID(0)))
  583. {
  584. si32 amount = getStack(SlotID(0)).getCount();
  585. handler.serializeInt("amount", amount, 0);
  586. }
  587. }
  588. else
  589. {
  590. si32 amount = 0;
  591. handler.serializeInt("amount", amount);
  592. auto hlp = std::make_unique<CStackInstance>(cb);
  593. hlp->setCount(amount);
  594. //type will be set during initialization
  595. putStack(SlotID(0), std::move(hlp));
  596. }
  597. resources.serializeJson(handler, "rewardResources");
  598. handler.serializeId("rewardArtifact", gainedArtifact, ArtifactID(ArtifactID::NONE));
  599. handler.serializeBool("noGrowing", notGrowingTeam);
  600. handler.serializeBool("neverFlees", neverFlees);
  601. handler.serializeStruct("rewardMessage", message);
  602. }
  603. VCMI_LIB_NAMESPACE_END