123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296 |
- /*
- * CGTownInstance.cpp, part of VCMI engine
- *
- * Authors: listed in file AUTHORS in main folder
- *
- * License: GNU General Public License v2.0 or later
- * Full text of license available in license.txt file, in main folder
- *
- */
- #include "StdInc.h"
- #include "CGTownInstance.h"
- #include "CGTownBuilding.h"
- #include "../spells/CSpellHandler.h"
- #include "../bonuses/Bonus.h"
- #include "../battle/IBattleInfoCallback.h"
- #include "../CConfigHandler.h"
- #include "../CGeneralTextHandler.h"
- #include "../IGameCallback.h"
- #include "../gameState/CGameState.h"
- #include "../mapping/CMap.h"
- #include "../CPlayerState.h"
- #include "../StartInfo.h"
- #include "../TerrainHandler.h"
- #include "../mapObjectConstructors/AObjectTypeHandler.h"
- #include "../mapObjectConstructors/CObjectClassesHandler.h"
- #include "../mapObjects/CGHeroInstance.h"
- #include "../modding/ModScope.h"
- #include "../networkPacks/StackLocation.h"
- #include "../networkPacks/PacksForClient.h"
- #include "../networkPacks/PacksForClientBattle.h"
- #include "../serializer/JsonSerializeFormat.h"
- VCMI_LIB_NAMESPACE_BEGIN
- std::vector<const CArtifact *> CGTownInstance::merchantArtifacts;
- std::vector<int> CGTownInstance::universitySkills;
- int CGTownInstance::getSightRadius() const //returns sight distance
- {
- auto ret = CBuilding::HEIGHT_NO_TOWER;
- for(const auto & bid : builtBuildings)
- {
- if(bid.IsSpecialOrGrail())
- {
- auto height = town->buildings.at(bid)->height;
- if(ret < height)
- ret = height;
- }
- }
- return ret;
- }
- void CGTownInstance::setPropertyDer(ui8 what, ui32 val)
- {
- ///this is freakin' overcomplicated solution
- switch (what)
- {
- case ObjProperty::STRUCTURE_ADD_VISITING_HERO:
- bonusingBuildings[val]->setProperty(ObjProperty::VISITORS, visitingHero->id.getNum());
- break;
- case ObjProperty::STRUCTURE_CLEAR_VISITORS:
- bonusingBuildings[val]->setProperty(ObjProperty::STRUCTURE_CLEAR_VISITORS, 0);
- break;
- case ObjProperty::STRUCTURE_ADD_GARRISONED_HERO: //add garrisoned hero to visitors
- bonusingBuildings[val]->setProperty(ObjProperty::VISITORS, garrisonHero->id.getNum());
- break;
- case ObjProperty::BONUS_VALUE_FIRST:
- bonusValue.first = val;
- break;
- case ObjProperty::BONUS_VALUE_SECOND:
- bonusValue.second = val;
- break;
- case ObjProperty::REWARD_RANDOMIZE:
- bonusingBuildings[val]->setProperty(ObjProperty::REWARD_RANDOMIZE, 0);
- break;
- }
- }
- CGTownInstance::EFortLevel CGTownInstance::fortLevel() const //0 - none, 1 - fort, 2 - citadel, 3 - castle
- {
- if (hasBuilt(BuildingID::CASTLE))
- return CASTLE;
- if (hasBuilt(BuildingID::CITADEL))
- return CITADEL;
- if (hasBuilt(BuildingID::FORT))
- return FORT;
- return NONE;
- }
- int CGTownInstance::hallLevel() const // -1 - none, 0 - village, 1 - town, 2 - city, 3 - capitol
- {
- if (hasBuilt(BuildingID::CAPITOL))
- return 3;
- if (hasBuilt(BuildingID::CITY_HALL))
- return 2;
- if (hasBuilt(BuildingID::TOWN_HALL))
- return 1;
- if (hasBuilt(BuildingID::VILLAGE_HALL))
- return 0;
- return -1;
- }
- int CGTownInstance::mageGuildLevel() const
- {
- if (hasBuilt(BuildingID::MAGES_GUILD_5))
- return 5;
- if (hasBuilt(BuildingID::MAGES_GUILD_4))
- return 4;
- if (hasBuilt(BuildingID::MAGES_GUILD_3))
- return 3;
- if (hasBuilt(BuildingID::MAGES_GUILD_2))
- return 2;
- if (hasBuilt(BuildingID::MAGES_GUILD_1))
- return 1;
- return 0;
- }
- int CGTownInstance::getHordeLevel(const int & HID) const//HID - 0 or 1; returns creature level or -1 if that horde structure is not present
- {
- return town->hordeLvl.at(HID);
- }
- int CGTownInstance::creatureGrowth(const int & level) const
- {
- return getGrowthInfo(level).totalGrowth();
- }
- GrowthInfo CGTownInstance::getGrowthInfo(int level) const
- {
- GrowthInfo ret;
- if (level<0 || level >=GameConstants::CREATURES_PER_TOWN)
- return ret;
- if (creatures[level].second.empty())
- return ret; //no dwelling
- const CCreature *creature = VLC->creh->objects[creatures[level].second.back()];
- const int base = creature->getGrowth();
- int castleBonus = 0;
- ret.entries.emplace_back(VLC->generaltexth->allTexts[590], base); // \n\nBasic growth %d"
- if (hasBuilt(BuildingID::CASTLE))
- ret.entries.emplace_back(subID, BuildingID::CASTLE, castleBonus = base);
- else if (hasBuilt(BuildingID::CITADEL))
- ret.entries.emplace_back(subID, BuildingID::CITADEL, castleBonus = base / 2);
- if(town->hordeLvl.at(0) == level)//horde 1
- if(hasBuilt(BuildingID::HORDE_1))
- ret.entries.emplace_back(subID, BuildingID::HORDE_1, creature->getHorde());
- if(town->hordeLvl.at(1) == level)//horde 2
- if(hasBuilt(BuildingID::HORDE_2))
- ret.entries.emplace_back(subID, BuildingID::HORDE_2, creature->getHorde());
- //statue-of-legion-like bonus: % to base+castle
- TConstBonusListPtr bonuses2 = getBonuses(Selector::type()(BonusType::CREATURE_GROWTH_PERCENT));
- for(const auto & b : *bonuses2)
- {
- const auto growth = b->val * (base + castleBonus) / 100;
- ret.entries.emplace_back(growth, b->Description(growth));
- }
- //other *-of-legion-like bonuses (%d to growth cumulative with grail)
- TConstBonusListPtr bonuses = getBonuses(Selector::typeSubtype(BonusType::CREATURE_GROWTH, BonusCustomSubtype::creatureLevel(level)));
- for(const auto & b : *bonuses)
- ret.entries.emplace_back(b->val, b->Description());
- int dwellingBonus = 0;
- if(const PlayerState *p = cb->getPlayerState(tempOwner, false))
- {
- dwellingBonus = getDwellingBonus(creatures[level].second, p->dwellings);
- }
- if(dwellingBonus)
- ret.entries.emplace_back(VLC->generaltexth->allTexts[591], dwellingBonus); // \nExternal dwellings %+d
- if(hasBuilt(BuildingID::GRAIL)) //grail - +50% to ALL (so far added) growth
- ret.entries.emplace_back(subID, BuildingID::GRAIL, ret.totalGrowth() / 2);
- return ret;
- }
- int CGTownInstance::getDwellingBonus(const std::vector<CreatureID>& creatureIds, const std::vector<ConstTransitivePtr<CGDwelling> >& dwellings) const
- {
- int totalBonus = 0;
- for (const auto& dwelling : dwellings)
- {
- for (const auto& creature : dwelling->creatures)
- {
- totalBonus += vstd::contains(creatureIds, creature.second[0]) ? 1 : 0;
- }
- }
- return totalBonus;
- }
- TResources CGTownInstance::dailyIncome() const
- {
- TResources ret;
- for(const auto & p : town->buildings)
- {
- BuildingID buildingUpgrade;
- for(const auto & p2 : town->buildings)
- {
- if (p2.second->upgrade == p.first)
- {
- buildingUpgrade = p2.first;
- }
- }
- if (!hasBuilt(buildingUpgrade)&&(hasBuilt(p.first)))
- {
- ret += p.second->produce;
- }
- }
- return ret;
- }
- bool CGTownInstance::hasFort() const
- {
- return hasBuilt(BuildingID::FORT);
- }
- bool CGTownInstance::hasCapitol() const
- {
- return hasBuilt(BuildingID::CAPITOL);
- }
- CGTownInstance::CGTownInstance():
- town(nullptr),
- builded(0),
- destroyed(0),
- identifier(0),
- alignmentToPlayer(PlayerColor::NEUTRAL)
- {
- this->setNodeType(CBonusSystemNode::TOWN);
- }
- CGTownInstance::~CGTownInstance()
- {
- for (auto & elem : bonusingBuildings)
- delete elem;
- }
- int CGTownInstance::spellsAtLevel(int level, bool checkGuild) const
- {
- if(checkGuild && mageGuildLevel() < level)
- return 0;
- int ret = 6 - level; //how many spells are available at this level
- if (hasBuilt(BuildingSubID::LIBRARY))
- ret++;
- return ret;
- }
- bool CGTownInstance::needsLastStack() const
- {
- return garrisonHero != nullptr;
- }
- void CGTownInstance::setOwner(const PlayerColor & player) const
- {
- removeCapitols(player);
- cb->setOwner(this, player);
- }
- void CGTownInstance::blockingDialogAnswered(const CGHeroInstance *hero, ui32 answer) const
- {
- for (auto building : bonusingBuildings)
- building->blockingDialogAnswered(hero, answer);
- }
- void CGTownInstance::onHeroVisit(const CGHeroInstance * h) const
- {
- if(cb->gameState()->getPlayerRelations( getOwner(), h->getOwner() ) == PlayerRelations::ENEMIES)
- {
- if(armedGarrison() || visitingHero)
- {
- const CGHeroInstance * defendingHero = visitingHero ? visitingHero : garrisonHero;
- const CArmedInstance * defendingArmy = defendingHero ? (CArmedInstance *)defendingHero : this;
- const bool isBattleOutside = isBattleOutsideTown(defendingHero);
- if(!isBattleOutside && visitingHero && defendingHero == visitingHero)
- {
- //we have two approaches to merge armies: mergeGarrisonOnSiege() and used in the CGameHandler::garrisonSwap(ObjectInstanceID tid)
- auto * nodeSiege = defendingHero->whereShouldBeAttachedOnSiege(isBattleOutside);
- if(nodeSiege == (CBonusSystemNode *)this)
- cb->swapGarrisonOnSiege(this->id);
- const_cast<CGHeroInstance *>(defendingHero)->inTownGarrison = false; //hack to return visitor from garrison after battle
- }
- cb->startBattlePrimary(h, defendingArmy, getSightCenter(), h, defendingHero, false, (isBattleOutside ? nullptr : this));
- }
- else
- {
- auto heroColor = h->getOwner();
- onTownCaptured(heroColor);
- if(cb->gameState()->getPlayerStatus(heroColor) == EPlayerStatus::WINNER)
- {
- return; //we just won game, we do not need to perform any extra actions
- //TODO: check how does H3 behave, visiting town on victory can affect campaigns (spells learned, +1 stat building visited)
- }
- cb->heroVisitCastle(this, h);
- }
- }
- else if(h->visitablePos() == visitablePos())
- {
- bool commander_recover = h->commander && !h->commander->alive;
- if (commander_recover) // rise commander from dead
- {
- SetCommanderProperty scp;
- scp.heroid = h->id;
- scp.which = SetCommanderProperty::ALIVE;
- scp.amount = 1;
- cb->sendAndApply(&scp);
- }
- cb->heroVisitCastle(this, h);
- // TODO(vmarkovtsev): implement payment for rising the commander
- if (commander_recover) // info window about commander
- {
- InfoWindow iw;
- iw.player = h->tempOwner;
- iw.text.appendRawString(h->commander->getName());
- iw.components.emplace_back(ComponentType::CREATURE, h->commander->getId(), h->commander->getCount());
- cb->showInfoDialog(&iw);
- }
- }
- else
- {
- logGlobal->error("%s visits allied town of %s from different pos?", h->getNameTranslated(), getNameTranslated());
- }
- }
- void CGTownInstance::onHeroLeave(const CGHeroInstance * h) const
- {
- //FIXME: find out why this issue appears on random maps
- if(visitingHero == h)
- {
- cb->stopHeroVisitCastle(this, h);
- logGlobal->trace("%s correctly left town %s", h->getNameTranslated(), getNameTranslated());
- }
- else
- logGlobal->warn("Warning, %s tries to leave the town %s but hero is not inside.", h->getNameTranslated(), getNameTranslated());
- }
- std::string CGTownInstance::getObjectName() const
- {
- return getNameTranslated() + ", " + town->faction->getNameTranslated();
- }
- bool CGTownInstance::townEnvisagesBuilding(BuildingSubID::EBuildingSubID subId) const
- {
- return town->getBuildingType(subId) != BuildingID::NONE;
- }
- void CGTownInstance::initOverriddenBids()
- {
- for(const auto & bid : builtBuildings)
- {
- const auto & overrideThem = town->buildings.at(bid)->overrideBids;
- for(const auto & overrideIt : overrideThem)
- overriddenBuildings.insert(overrideIt);
- }
- }
- bool CGTownInstance::isBonusingBuildingAdded(BuildingID bid) const
- {
- auto present = std::find_if(bonusingBuildings.begin(), bonusingBuildings.end(), [&](CGTownBuilding* building)
- {
- return building->getBuildingType().num == bid;
- });
- return present != bonusingBuildings.end();
- }
- void CGTownInstance::addTownBonuses(CRandomGenerator & rand)
- {
- for(const auto & kvp : town->buildings)
- {
- if(vstd::contains(overriddenBuildings, kvp.first))
- continue;
- if(kvp.second->IsVisitingBonus())
- bonusingBuildings.push_back(new CTownBonus(kvp.second->bid, kvp.second->subId, this));
- if(kvp.second->IsWeekBonus())
- bonusingBuildings.push_back(new COPWBonus(kvp.second->bid, kvp.second->subId, this));
-
- if(kvp.second->subId == BuildingSubID::CUSTOM_VISITING_REWARD)
- bonusingBuildings.push_back(new CTownRewardableBuilding(kvp.second->bid, kvp.second->subId, this, rand));
- }
- }
- DamageRange CGTownInstance::getTowerDamageRange() const
- {
- assert(hasBuilt(BuildingID::CASTLE));
- // http://heroes.thelazy.net/wiki/Arrow_tower
- // base damage, irregardless of town level
- static constexpr int baseDamage = 6;
- // extra damage, for each building in town
- static constexpr int extraDamage = 1;
- const int minDamage = baseDamage + extraDamage * getTownLevel();
- return {
- minDamage,
- minDamage * 2
- };
- }
- DamageRange CGTownInstance::getKeepDamageRange() const
- {
- assert(hasBuilt(BuildingID::CITADEL));
- // http://heroes.thelazy.net/wiki/Arrow_tower
- // base damage, irregardless of town level
- static constexpr int baseDamage = 10;
- // extra damage, for each building in town
- static constexpr int extraDamage = 2;
- const int minDamage = baseDamage + extraDamage * getTownLevel();
- return {
- minDamage,
- minDamage * 2
- };
- }
- void CGTownInstance::deleteTownBonus(BuildingID bid)
- {
- size_t i = 0;
- CGTownBuilding * freeIt = nullptr;
- for(i = 0; i != bonusingBuildings.size(); i++)
- {
- if(bonusingBuildings[i]->getBuildingType() == bid)
- {
- freeIt = bonusingBuildings[i];
- break;
- }
- }
- if(freeIt == nullptr)
- return;
- auto building = town->buildings.at(bid);
- auto isVisitingBonus = building->IsVisitingBonus();
- auto isWeekBonus = building->IsWeekBonus();
- if(!isVisitingBonus && !isWeekBonus)
- return;
- bonusingBuildings.erase(bonusingBuildings.begin() + i);
- delete freeIt;
- }
- FactionID CGTownInstance::randomizeFaction(CRandomGenerator & rand)
- {
- if(getOwner().isValidPlayer())
- return cb->gameState()->scenarioOps->getIthPlayersSettings(getOwner()).castle;
- if(alignmentToPlayer.isValidPlayer())
- return cb->gameState()->scenarioOps->getIthPlayersSettings(alignmentToPlayer).castle;
- std::vector<FactionID> potentialPicks;
- for (FactionID faction(0); faction < VLC->townh->size(); ++faction)
- if (VLC->factions()->getById(faction)->hasTown())
- potentialPicks.push_back(faction);
- assert(!potentialPicks.empty());
- return *RandomGeneratorUtil::nextItem(potentialPicks, rand);
- }
- void CGTownInstance::pickRandomObject(CRandomGenerator & rand)
- {
- assert(ID == MapObjectID::TOWN || ID == MapObjectID::RANDOM_TOWN);
- if (ID == MapObjectID::RANDOM_TOWN)
- {
- ID = MapObjectID::TOWN;
- subID = randomizeFaction(rand);
- }
- assert(ID == Obj::TOWN); // just in case
- setType(ID, subID);
- town = (*VLC->townh)[subID]->town;
- randomizeArmy(subID);
- updateAppearance();
- }
- void CGTownInstance::initObj(CRandomGenerator & rand) ///initialize town structures
- {
- blockVisit = true;
- if(townEnvisagesBuilding(BuildingSubID::PORTAL_OF_SUMMONING)) //Dungeon for example
- creatures.resize(GameConstants::CREATURES_PER_TOWN + 1);
- else
- creatures.resize(GameConstants::CREATURES_PER_TOWN);
- for (int level = 0; level < GameConstants::CREATURES_PER_TOWN; level++)
- {
- BuildingID buildID = BuildingID(BuildingID::DWELL_FIRST + level);
- int upgradeNum = 0;
- for (; town->buildings.count(buildID); upgradeNum++, buildID.advance(GameConstants::CREATURES_PER_TOWN))
- {
- if (hasBuilt(buildID) && town->creatures.at(level).size() > upgradeNum)
- creatures[level].second.push_back(town->creatures[level][upgradeNum]);
- }
- }
- initOverriddenBids();
- addTownBonuses(rand); //add special bonuses from buildings to the bonusingBuildings vector.
- recreateBuildingsBonuses();
- updateAppearance();
- }
- void CGTownInstance::newTurn(CRandomGenerator & rand) const
- {
- if (cb->getDate(Date::DAY_OF_WEEK) == 1) //reset on new week
- {
- //give resources if there's a Mystic Pond
- if (hasBuilt(BuildingSubID::MYSTIC_POND)
- && cb->getDate(Date::DAY) != 1
- && (tempOwner.isValidPlayer())
- )
- {
- int resID = rand.nextInt(2, 5); //bonus to random rare resource
- resID = (resID==2)?1:resID;
- int resVal = rand.nextInt(1, 4);//with size 1..4
- cb->giveResource(tempOwner, static_cast<EGameResID>(resID), resVal);
- cb->setObjProperty (id, ObjProperty::BONUS_VALUE_FIRST, resID);
- cb->setObjProperty (id, ObjProperty::BONUS_VALUE_SECOND, resVal);
- }
-
- for(const auto * manaVortex : getBonusingBuildings(BuildingSubID::MANA_VORTEX))
- cb->setObjProperty(id, ObjProperty::STRUCTURE_CLEAR_VISITORS, manaVortex->indexOnTV); //reset visitors for Mana Vortex
- //get Mana Vortex or Stables bonuses
- //same code is in the CGameHandler::buildStructure method
- if (visitingHero != nullptr)
- cb->visitCastleObjects(this, visitingHero);
- if (garrisonHero != nullptr)
- cb->visitCastleObjects(this, garrisonHero);
- if (tempOwner == PlayerColor::NEUTRAL) //garrison growth for neutral towns
- {
- std::vector<SlotID> nativeCrits; //slots
- for(const auto & elem : Slots())
- {
- if (elem.second->type->getFaction() == getFaction()) //native
- {
- nativeCrits.push_back(elem.first); //collect matching slots
- }
- }
- if(!nativeCrits.empty())
- {
- SlotID pos = *RandomGeneratorUtil::nextItem(nativeCrits, rand);
- StackLocation sl(this, pos);
-
- const CCreature *c = getCreature(pos);
- if (rand.nextInt(99) < 90 || c->upgrades.empty()) //increase number if no upgrade available
- {
- cb->changeStackCount(sl, c->getGrowth());
- }
- else //upgrade
- {
- cb->changeStackType(sl, VLC->creh->objects[*c->upgrades.begin()]);
- }
- }
- if ((stacksCount() < GameConstants::ARMY_SIZE && rand.nextInt(99) < 25) || Slots().empty()) //add new stack
- {
- int i = rand.nextInt(std::min(GameConstants::CREATURES_PER_TOWN, cb->getDate(Date::MONTH) << 1) - 1);
- if (!town->creatures[i].empty())
- {
- CreatureID c = town->creatures[i][0];
- SlotID n;
-
- TQuantity count = creatureGrowth(i);
- if (!count) // no dwelling
- count = VLC->creatures()->getByIndex(c)->getGrowth();
-
- {//no lower tiers or above current month
-
- if ((n = getSlotFor(c)).validSlot())
- {
- StackLocation sl(this, n);
- if (slotEmpty(n))
- cb->insertNewStack(sl, VLC->creh->objects[c], count);
- else //add to existing
- cb->changeStackCount(sl, count);
- }
- }
- }
- }
- }
- }
-
- for(const auto * rewardableBuilding : getBonusingBuildings(BuildingSubID::CUSTOM_VISITING_REWARD))
- rewardableBuilding->newTurn(rand);
- }
- /*
- int3 CGTownInstance::getSightCenter() const
- {
- return pos - int3(2,0,0);
- }
- */
- bool CGTownInstance::passableFor(PlayerColor color) const
- {
- if (!armedGarrison())//empty castle - anyone can visit
- return true;
- if ( tempOwner == PlayerColor::NEUTRAL )//neutral guarded - no one can visit
- return false;
- return cb->getPlayerRelations(tempOwner, color) != PlayerRelations::ENEMIES;
- }
- void CGTownInstance::getOutOffsets( std::vector<int3> &offsets ) const
- {
- offsets = {int3(-1,2,0), int3(+1,2,0)};
- }
- CGTownInstance::EGeneratorState CGTownInstance::shipyardStatus() const
- {
- if (!hasBuilt(BuildingID::SHIPYARD))
- return EGeneratorState::UNKNOWN;
- return IShipyard::shipyardStatus();
- }
- const IObjectInterface * CGTownInstance::getObject() const
- {
- return this;
- }
- void CGTownInstance::mergeGarrisonOnSiege() const
- {
- auto getWeakestStackSlot = [&](ui64 powerLimit)
- {
- std::vector<SlotID> weakSlots;
- auto stacksList = visitingHero->stacks;
- std::pair<SlotID, CStackInstance *> pair;
- while(!stacksList.empty())
- {
- pair = *vstd::minElementByFun(stacksList, [&](const std::pair<SlotID, CStackInstance *> & elem) { return elem.second->getPower(); });
- if(powerLimit > pair.second->getPower() &&
- (weakSlots.empty() || pair.second->getPower() == visitingHero->getStack(weakSlots.front()).getPower()))
- {
- weakSlots.push_back(pair.first);
- stacksList.erase(pair.first);
- }
- else
- break;
- }
- if(!weakSlots.empty())
- return *std::max_element(weakSlots.begin(), weakSlots.end());
- return SlotID();
- };
- auto count = static_cast<int>(stacks.size());
- for(int i = 0; i < count; i++)
- {
- auto pair = *vstd::maxElementByFun(stacks, [&](const std::pair<SlotID, CStackInstance *> & elem)
- {
- ui64 power = elem.second->getPower();
- auto dst = visitingHero->getSlotFor(elem.second->getCreatureID());
- if(dst.validSlot() && visitingHero->hasStackAtSlot(dst))
- power += visitingHero->getStack(dst).getPower();
- return power;
- });
- auto dst = visitingHero->getSlotFor(pair.second->getCreatureID());
- if(dst.validSlot())
- cb->moveStack(StackLocation(this, pair.first), StackLocation(visitingHero, dst), -1);
- else
- {
- dst = getWeakestStackSlot(static_cast<int>(pair.second->getPower()));
- if(dst.validSlot())
- cb->swapStacks(StackLocation(this, pair.first), StackLocation(visitingHero, dst));
- }
- }
- }
- void CGTownInstance::removeCapitols(const PlayerColor & owner) const
- {
- if (hasCapitol()) // search if there's an older capitol
- {
- PlayerState* state = cb->gameState()->getPlayerState(owner); //get all towns owned by player
- for (auto i = state->towns.cbegin(); i < state->towns.cend(); ++i)
- {
- if (*i != this && (*i)->hasCapitol())
- {
- RazeStructures rs;
- rs.tid = id;
- rs.bid.insert(BuildingID::CAPITOL);
- rs.destroyed = destroyed;
- cb->sendAndApply(&rs);
- return;
- }
- }
- }
- }
- void CGTownInstance::clearArmy() const
- {
- while(!stacks.empty())
- {
- cb->eraseStack(StackLocation(this, stacks.begin()->first));
- }
- }
- BoatId CGTownInstance::getBoatType() const
- {
- return town->faction->boatType;
- }
- int CGTownInstance::getMarketEfficiency() const
- {
- if(!hasBuiltSomeTradeBuilding())
- return 0;
- const PlayerState *p = cb->getPlayerState(tempOwner);
- assert(p);
- int marketCount = 0;
- for(const CGTownInstance *t : p->towns)
- if(t->hasBuiltSomeTradeBuilding())
- marketCount++;
- return marketCount;
- }
- bool CGTownInstance::allowsTrade(EMarketMode mode) const
- {
- switch(mode)
- {
- case EMarketMode::RESOURCE_RESOURCE:
- case EMarketMode::RESOURCE_PLAYER:
- return hasBuilt(BuildingID::MARKETPLACE);
- case EMarketMode::ARTIFACT_RESOURCE:
- case EMarketMode::RESOURCE_ARTIFACT:
- return hasBuilt(BuildingSubID::ARTIFACT_MERCHANT);
- case EMarketMode::CREATURE_RESOURCE:
- return hasBuilt(BuildingSubID::FREELANCERS_GUILD);
- case EMarketMode::CREATURE_UNDEAD:
- return hasBuilt(BuildingSubID::CREATURE_TRANSFORMER);
- case EMarketMode::RESOURCE_SKILL:
- return hasBuilt(BuildingSubID::MAGIC_UNIVERSITY);
- default:
- assert(0);
- return false;
- }
- }
- std::vector<int> CGTownInstance::availableItemsIds(EMarketMode mode) const
- {
- if(mode == EMarketMode::RESOURCE_ARTIFACT)
- {
- std::vector<int> ret;
- for(const CArtifact *a : merchantArtifacts)
- if(a)
- ret.push_back(a->getId());
- else
- ret.push_back(-1);
- return ret;
- }
- else if ( mode == EMarketMode::RESOURCE_SKILL )
- {
- return universitySkills;
- }
- else
- return IMarket::availableItemsIds(mode);
- }
- void CGTownInstance::updateAppearance()
- {
- auto terrain = cb->gameState()->getTile(visitablePos())->terType->getId();
- //FIXME: not the best way to do this
- auto app = getObjectHandler()->getOverride(terrain, this);
- if (app)
- appearance = app;
- }
- std::string CGTownInstance::nodeName() const
- {
- return "Town (" + (town ? town->faction->getNameTranslated() : "unknown") + ") of " + getNameTranslated();
- }
- void CGTownInstance::deserializationFix()
- {
- attachTo(townAndVis);
- //Hero is already handled by CGameState::attachArmedObjects
- // if(visitingHero)
- // visitingHero->attachTo(&townAndVis);
- // if(garrisonHero)
- // garrisonHero->attachTo(this);
- }
- void CGTownInstance::updateMoraleBonusFromArmy()
- {
- auto b = getExportedBonusList().getFirst(Selector::sourceType()(BonusSource::ARMY).And(Selector::type()(BonusType::MORALE)));
- if(!b)
- {
- b = std::make_shared<Bonus>(BonusDuration::PERMANENT, BonusType::MORALE, BonusSource::ARMY, 0, BonusSourceID());
- addNewBonus(b);
- }
- if (garrisonHero)
- {
- b->val = 0;
- CBonusSystemNode::treeHasChanged();
- }
- else
- CArmedInstance::updateMoraleBonusFromArmy();
- }
- void CGTownInstance::recreateBuildingsBonuses()
- {
- BonusList bl;
- getExportedBonusList().getBonuses(bl, Selector::sourceType()(BonusSource::TOWN_STRUCTURE));
- for(const auto & b : bl)
- removeBonus(b);
- for(const auto & bid : builtBuildings)
- {
- if(vstd::contains(overriddenBuildings, bid)) //tricky! -> checks tavern only if no bratherhood of sword
- continue;
- auto building = town->buildings.at(bid);
- if(building->buildingBonuses.empty())
- continue;
- for(auto & bonus : building->buildingBonuses)
- addNewBonus(bonus);
- }
- }
- void CGTownInstance::setVisitingHero(CGHeroInstance *h)
- {
- if(visitingHero.get() == h)
- return;
-
- if(h)
- {
- PlayerState *p = cb->gameState()->getPlayerState(h->tempOwner);
- assert(p);
- h->detachFrom(*p);
- h->attachTo(townAndVis);
- visitingHero = h;
- h->visitedTown = this;
- h->inTownGarrison = false;
- }
- else
- {
- PlayerState *p = cb->gameState()->getPlayerState(visitingHero->tempOwner);
- visitingHero->visitedTown = nullptr;
- visitingHero->detachFrom(townAndVis);
- visitingHero->attachTo(*p);
- visitingHero = nullptr;
- }
- }
- void CGTownInstance::setGarrisonedHero(CGHeroInstance *h)
- {
- if(garrisonHero.get() == h)
- return;
-
- if(h)
- {
- PlayerState *p = cb->gameState()->getPlayerState(h->tempOwner);
- assert(p);
- h->detachFrom(*p);
- h->attachTo(*this);
- garrisonHero = h;
- h->visitedTown = this;
- h->inTownGarrison = true;
- }
- else
- {
- PlayerState *p = cb->gameState()->getPlayerState(garrisonHero->tempOwner);
- garrisonHero->visitedTown = nullptr;
- garrisonHero->inTownGarrison = false;
- garrisonHero->detachFrom(*this);
- garrisonHero->attachTo(*p);
- garrisonHero = nullptr;
- }
- updateMoraleBonusFromArmy(); //avoid giving morale bonus for same army twice
- }
- bool CGTownInstance::armedGarrison() const
- {
- return !stacks.empty() || garrisonHero;
- }
- const CTown * CGTownInstance::getTown() const
- {
- if(ID == Obj::RANDOM_TOWN)
- return VLC->townh->randomTown;
- else
- {
- if(nullptr == town)
- {
- return (*VLC->townh)[subID]->town;
- }
- else
- return town;
- }
- }
- int CGTownInstance::getTownLevel() const
- {
- // count all buildings that are not upgrades
- int level = 0;
- for(const auto & bid : builtBuildings)
- {
- if(town->buildings.at(bid)->upgrade == BuildingID::NONE)
- level++;
- }
- return level;
- }
- CBonusSystemNode & CGTownInstance::whatShouldBeAttached()
- {
- return townAndVis;
- }
- std::string CGTownInstance::getNameTranslated() const
- {
- return VLC->generaltexth->translate(nameTextId);
- }
- void CGTownInstance::setNameTextId( const std::string & newName )
- {
- nameTextId = newName;
- }
- const CArmedInstance * CGTownInstance::getUpperArmy() const
- {
- if(garrisonHero)
- return garrisonHero;
- return this;
- }
- std::vector<const CGTownBuilding *> CGTownInstance::getBonusingBuildings(BuildingSubID::EBuildingSubID subId) const
- {
- std::vector<const CGTownBuilding *> ret;
- for(auto * const building : bonusingBuildings)
- {
- if(building->getBuildingSubtype() == subId)
- ret.push_back(building);
- }
- return ret;
- }
- bool CGTownInstance::hasBuiltSomeTradeBuilding() const
- {
- for(const auto & bid : builtBuildings)
- {
- if(town->buildings.at(bid)->IsTradeBuilding())
- return true;
- }
- return false;
- }
- bool CGTownInstance::hasBuilt(BuildingSubID::EBuildingSubID buildingID) const
- {
- for(const auto & bid : builtBuildings)
- {
- if(town->buildings.at(bid)->subId == buildingID)
- return true;
- }
- return false;
- }
- bool CGTownInstance::hasBuilt(const BuildingID & buildingID) const
- {
- return vstd::contains(builtBuildings, buildingID);
- }
- bool CGTownInstance::hasBuilt(const BuildingID & buildingID, int townID) const
- {
- if (townID == town->faction->getIndex() || townID == ETownType::ANY)
- return hasBuilt(buildingID);
- return false;
- }
- TResources CGTownInstance::getBuildingCost(const BuildingID & buildingID) const
- {
- if (vstd::contains(town->buildings, buildingID))
- return town->buildings.at(buildingID)->resources;
- else
- {
- logGlobal->error("Town %s at %s has no possible building %d!", getNameTranslated(), pos.toString(), buildingID.toEnum());
- return TResources();
- }
- }
- CBuilding::TRequired CGTownInstance::genBuildingRequirements(const BuildingID & buildID, bool deep) const
- {
- const CBuilding * building = town->buildings.at(buildID);
- //TODO: find better solution to prevent infinite loops
- std::set<BuildingID> processed;
- std::function<CBuilding::TRequired::Variant(const BuildingID &)> dependTest =
- [&](const BuildingID & id) -> CBuilding::TRequired::Variant
- {
- if (town->buildings.count(id) == 0)
- {
- logMod->error("Invalid building ID %d in building dependencies!", id.getNum());
- return CBuilding::TRequired::OperatorAll();
- }
- const CBuilding * build = town->buildings.at(id);
- CBuilding::TRequired::OperatorAll requirements;
- if (!hasBuilt(id))
- {
- if (deep)
- requirements.expressions.emplace_back(id);
- else
- return id;
- }
- if(!vstd::contains(processed, id))
- {
- processed.insert(id);
- if (build->upgrade != BuildingID::NONE)
- requirements.expressions.push_back(dependTest(build->upgrade));
- requirements.expressions.push_back(build->requirements.morph(dependTest));
- }
- return requirements;
- };
- CBuilding::TRequired::OperatorAll requirements;
- if (building->upgrade != BuildingID::NONE)
- {
- const CBuilding * upgr = town->buildings.at(building->upgrade);
- requirements.expressions.push_back(dependTest(upgr->bid));
- processed.clear();
- }
- requirements.expressions.push_back(building->requirements.morph(dependTest));
- CBuilding::TRequired::Variant variant(requirements);
- CBuilding::TRequired ret(variant);
- ret.minimize();
- return ret;
- }
- void CGTownInstance::addHeroToStructureVisitors(const CGHeroInstance *h, si64 structureInstanceID ) const
- {
- if(visitingHero == h)
- cb->setObjProperty(id, ObjProperty::STRUCTURE_ADD_VISITING_HERO, structureInstanceID); //add to visitors
- else if(garrisonHero == h)
- cb->setObjProperty(id, ObjProperty::STRUCTURE_ADD_GARRISONED_HERO, structureInstanceID); //then it must be garrisoned hero
- else
- {
- //should never ever happen
- logGlobal->error("Cannot add hero %s to visitors of structure # %d", h->getNameTranslated(), structureInstanceID);
- throw std::runtime_error("internal error");
- }
- }
- void CGTownInstance::battleFinished(const CGHeroInstance * hero, const BattleResult & result) const
- {
- if(result.winner == BattleSide::ATTACKER)
- {
- clearArmy();
- onTownCaptured(hero->getOwner());
- }
- }
- void CGTownInstance::onTownCaptured(const PlayerColor & winner) const
- {
- setOwner(winner);
- cb->changeFogOfWar(getSightCenter(), getSightRadius(), winner, ETileVisibility::REVEALED);
- }
- void CGTownInstance::afterAddToMap(CMap * map)
- {
- map->towns.emplace_back(this);
- }
- void CGTownInstance::afterRemoveFromMap(CMap * map)
- {
- vstd::erase_if_present(map->towns, this);
- }
- void CGTownInstance::reset()
- {
- CGTownInstance::merchantArtifacts.clear();
- CGTownInstance::universitySkills.clear();
- }
- void CGTownInstance::serializeJsonOptions(JsonSerializeFormat & handler)
- {
- CGObjectInstance::serializeJsonOwner(handler);
- if(!handler.saving)
- handler.serializeEnum("tightFormation", formation, NArmyFormation::names); //for old format
- CArmedInstance::serializeJsonOptions(handler);
- handler.serializeString("name", nameTextId);
- {
- auto decodeBuilding = [this](const std::string & identifier) -> si32
- {
- auto rawId = VLC->identifiers()->getIdentifier(ModScope::scopeMap(), getTown()->getBuildingScope(), identifier);
- if(rawId)
- return rawId.value();
- else
- return -1;
- };
- auto encodeBuilding = [this](si32 index) -> std::string
- {
- return getTown()->buildings.at(BuildingID(index))->getJsonKey();
- };
- const std::set<si32> standard = getTown()->getAllBuildings();//by default all buildings are allowed
- JsonSerializeFormat::LICSet buildingsLIC(standard, decodeBuilding, encodeBuilding);
- if(handler.saving)
- {
- bool customBuildings = false;
- boost::logic::tribool hasFort(false);
- for(const BuildingID & id : forbiddenBuildings)
- {
- buildingsLIC.none.insert(id);
- customBuildings = true;
- }
- for(const BuildingID & id : builtBuildings)
- {
- if(id == BuildingID::DEFAULT)
- continue;
- const CBuilding * building = getTown()->buildings.at(id);
- if(building->mode == CBuilding::BUILD_AUTO)
- continue;
- if(id == BuildingID::FORT)
- hasFort = true;
- buildingsLIC.all.insert(id);
- customBuildings = true;
- }
- if(customBuildings)
- handler.serializeLIC("buildings", buildingsLIC);
- else
- handler.serializeBool("hasFort",hasFort);
- }
- else
- {
- handler.serializeLIC("buildings", buildingsLIC);
- builtBuildings.insert(BuildingID::VILLAGE_HALL);
- if(buildingsLIC.none.empty() && buildingsLIC.all.empty())
- {
- builtBuildings.insert(BuildingID::DEFAULT);
- bool hasFort = false;
- handler.serializeBool("hasFort",hasFort);
- if(hasFort)
- builtBuildings.insert(BuildingID::FORT);
- }
- else
- {
- for(const si32 item : buildingsLIC.none)
- forbiddenBuildings.insert(BuildingID(item));
- for(const si32 item : buildingsLIC.all)
- builtBuildings.insert(BuildingID(item));
- }
- }
- }
- {
- std::vector<bool> standard = VLC->spellh->getDefaultAllowed();
- JsonSerializeFormat::LIC spellsLIC(standard, SpellID::decode, SpellID::encode);
- if(handler.saving)
- {
- for(const SpellID & id : possibleSpells)
- spellsLIC.any[id.num] = true;
- for(const SpellID & id : obligatorySpells)
- spellsLIC.all[id.num] = true;
- }
- handler.serializeLIC("spells", spellsLIC);
- if(!handler.saving)
- {
- possibleSpells.clear();
- for(si32 idx = 0; idx < spellsLIC.any.size(); idx++)
- {
- if(spellsLIC.any[idx])
- possibleSpells.emplace_back(idx);
- }
- obligatorySpells.clear();
- for(si32 idx = 0; idx < spellsLIC.all.size(); idx++)
- {
- if(spellsLIC.all[idx])
- obligatorySpells.emplace_back(idx);
- }
- }
- }
- }
- FactionID CGTownInstance::getFaction() const
- {
- return town->faction->getId();
- }
- TerrainId CGTownInstance::getNativeTerrain() const
- {
- return town->faction->getNativeTerrain();
- }
- GrowthInfo::Entry::Entry(const std::string &format, int _count)
- : count(_count)
- {
- description = boost::str(boost::format(format) % count);
- }
- GrowthInfo::Entry::Entry(int subID, const BuildingID & building, int _count): count(_count)
- {
- description = boost::str(boost::format("%s %+d") % (*VLC->townh)[subID]->town->buildings.at(building)->getNameTranslated() % count);
- }
- GrowthInfo::Entry::Entry(int _count, std::string fullDescription):
- count(_count),
- description(std::move(fullDescription))
- {
- }
- CTownAndVisitingHero::CTownAndVisitingHero()
- {
- setNodeType(TOWN_AND_VISITOR);
- }
- int GrowthInfo::totalGrowth() const
- {
- int ret = 0;
- for(const Entry &entry : entries)
- ret += entry.count;
- return ret;
- }
- void CGTownInstance::fillUpgradeInfo(UpgradeInfo & info, const CStackInstance &stack) const
- {
- for(const CGTownInstance::TCreaturesSet::value_type & dwelling : creatures)
- {
- if (vstd::contains(dwelling.second, stack.type->getId())) //Dwelling with our creature
- {
- for(const auto & upgrID : dwelling.second)
- {
- if(vstd::contains(stack.type->upgrades, upgrID)) //possible upgrade
- {
- info.newID.push_back(upgrID);
- info.cost.push_back(upgrID.toCreature()->getFullRecruitCost() - stack.type->getFullRecruitCost());
- }
- }
- }
- }
- }
- VCMI_LIB_NAMESPACE_END
|