1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509 |
- #include "StdInc.h"
- #include "CBattleCallback.h"
- #include "BattleState.h"
- #include "CGameState.h"
- #include "NetPacks.h"
- #include "CSpellHandler.h"
- #include "VCMI_Lib.h"
- #include "CTownHandler.h"
- /*
- * CBattleCallback.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
- *
- */
- #define RETURN_IF_NOT_BATTLE(X) if(!duringBattle()) {logGlobal->errorStream() << __FUNCTION__ << " called when no battle!"; return X; }
- namespace SiegeStuffThatShouldBeMovedToHandlers // <=== TODO
- {
- static void retreiveTurretDamageRange(const CGTownInstance * town, const CStack *turret, double &outMinDmg, double &outMaxDmg)
- {
- assert(turret->getCreature()->idNumber == CreatureID::ARROW_TOWERS);
- assert(town);
- assert(turret->position >= -4 && turret->position <= -2);
- float multiplier = (turret->position == -2) ? 1 : 0.5;
- int baseMin = 6;
- int baseMax = 10;
- outMinDmg = multiplier * (baseMin + town->getTownLevel() * 2);
- outMaxDmg = multiplier * (baseMax + town->getTownLevel() * 3);
- }
- static BattleHex lineToWallHex(int line) //returns hex with wall in given line (y coordinate)
- {
- static const BattleHex lineToHex[] = {12, 29, 45, 62, 78, 95, 112, 130, 147, 165, 182};
- return lineToHex[line];
- }
- static bool sameSideOfWall(BattleHex pos1, BattleHex pos2)
- {
- const int wallInStackLine = lineToWallHex(pos1.getY());
- const int wallInDestLine = lineToWallHex(pos2.getY());
- const bool stackLeft = pos1 < wallInStackLine;
- const bool destLeft = pos2 < wallInDestLine;
- return stackLeft != destLeft;
- }
- // parts of wall
- static const std::pair<int, EWallPart::EWallPart> wallParts[] =
- {
- std::make_pair(50, EWallPart::KEEP),
- std::make_pair(183, EWallPart::BOTTOM_TOWER),
- std::make_pair(182, EWallPart::BOTTOM_WALL),
- std::make_pair(130, EWallPart::BELOW_GATE),
- std::make_pair(62, EWallPart::OVER_GATE),
- std::make_pair(29, EWallPart::UPPER_WALL),
- std::make_pair(12, EWallPart::UPPER_TOWER),
- std::make_pair(95, EWallPart::INDESTRUCTIBLE_PART_OF_GATE),
- std::make_pair(96, EWallPart::GATE),
- std::make_pair(45, EWallPart::INDESTRUCTIBLE_PART),
- std::make_pair(78, EWallPart::INDESTRUCTIBLE_PART),
- std::make_pair(112, EWallPart::INDESTRUCTIBLE_PART),
- std::make_pair(147, EWallPart::INDESTRUCTIBLE_PART)
- };
- static EWallPart::EWallPart hexToWallPart(BattleHex hex)
- {
- for(auto & elem : wallParts)
- {
- if(elem.first == hex)
- return elem.second;
- }
- return EWallPart::INVALID; //not found!
- }
- static BattleHex WallPartToHex(EWallPart::EWallPart part)
- {
- for(auto & elem : wallParts)
- {
- if(elem.second == part)
- return elem.first;
- }
- return BattleHex::INVALID; //not found!
- }
- }
- using namespace SiegeStuffThatShouldBeMovedToHandlers;
- boost::shared_mutex& CCallbackBase::getGsMutex()
- {
- return *gs->mx;
- }
- bool CCallbackBase::duringBattle() const
- {
- return getBattle() != nullptr;
- }
- void CCallbackBase::setBattle(const BattleInfo *B)
- {
- battle = B;
- }
- boost::optional<PlayerColor> CCallbackBase::getPlayerID() const
- {
- return player;
- }
- ETerrainType CBattleInfoEssentials::battleTerrainType() const
- {
- RETURN_IF_NOT_BATTLE(ETerrainType::WRONG);
- return getBattle()->terrainType;
- }
- BFieldType CBattleInfoEssentials::battleGetBattlefieldType() const
- {
- RETURN_IF_NOT_BATTLE(BFieldType::NONE);
- return getBattle()->battlefieldType;
- }
- std::vector<shared_ptr<const CObstacleInstance> > CBattleInfoEssentials::battleGetAllObstacles(boost::optional<BattlePerspective::BattlePerspective> perspective /*= boost::none*/) const
- {
- std::vector<shared_ptr<const CObstacleInstance> > ret;
- RETURN_IF_NOT_BATTLE(ret);
- if(!perspective)
- {
- //if no particular perspective request, use default one
- perspective = battleGetMySide();
- }
- else
- {
- if(!!player && *perspective != battleGetMySide())
- {
- logGlobal->errorStream() << "Unauthorized access attempt!";
- assert(0); //I want to notice if that happens
- //perspective = battleGetMySide();
- }
- }
- for(auto oi : getBattle()->obstacles)
- {
- if(getBattle()->battleIsObstacleVisibleForSide(*oi, *perspective))
- ret.push_back(oi);
- }
- return ret;
- }
- bool CBattleInfoEssentials::battleIsObstacleVisibleForSide(const CObstacleInstance & coi, BattlePerspective::BattlePerspective side) const
- {
- RETURN_IF_NOT_BATTLE(false);
- return side == BattlePerspective::ALL_KNOWING || coi.visibleForSide(side, battleHasNativeStack(side));
- }
- bool CBattleInfoEssentials::battleHasNativeStack(ui8 side) const
- {
- RETURN_IF_NOT_BATTLE(false);
- for(const CStack *s : battleGetAllStacks())
- {
- if(s->attackerOwned == !side && s->getCreature()->isItNativeTerrain(getBattle()->terrainType))
- return true;
- }
- return false;
- }
- TStacks CBattleInfoEssentials::battleGetAllStacks(bool includeTurrets /*= false*/) const /*returns all stacks, alive or dead or undead or mechanical :) */
- {
- TStacks ret;
- RETURN_IF_NOT_BATTLE(ret);
- boost::copy(getBattle()->stacks, std::back_inserter(ret));
- if(!includeTurrets)
- vstd::erase_if(ret, [](const CStack *stack) { return stack->type->idNumber == CreatureID::ARROW_TOWERS; });
- return ret;
- }
- TStacks CBattleInfoEssentials::battleAliveStacks() const
- {
- TStacks ret;
- vstd::copy_if(battleGetAllStacks(), std::back_inserter(ret), [](const CStack *s){ return s->alive(); });
- return ret;
- }
- TStacks CBattleInfoEssentials::battleAliveStacks(ui8 side) const
- {
- TStacks ret;
- vstd::copy_if(battleGetAllStacks(), std::back_inserter(ret), [=](const CStack *s){ return s->alive() && s->attackerOwned == !side; });
- return ret;
- }
- int CBattleInfoEssentials::battleGetMoatDmg() const
- {
- RETURN_IF_NOT_BATTLE(0);
- auto town = getBattle()->town;
- if(!town)
- return 0;
- return town->town->moatDamage;
- }
- const CGTownInstance * CBattleInfoEssentials::battleGetDefendedTown() const
- {
- RETURN_IF_NOT_BATTLE(nullptr);
- if(!getBattle() || getBattle()->town == nullptr)
- return nullptr;
- return getBattle()->town;
- }
- BattlePerspective::BattlePerspective CBattleInfoEssentials::battleGetMySide() const
- {
- RETURN_IF_NOT_BATTLE(BattlePerspective::INVALID);
- if(!player)
- return BattlePerspective::ALL_KNOWING;
- if(*player == getBattle()->sides[0].color)
- return BattlePerspective::LEFT_SIDE;
- if(*player == getBattle()->sides[1].color)
- return BattlePerspective::RIGHT_SIDE;
- logGlobal->errorStream() << "Cannot find player " << *player << " in battle!";
- return BattlePerspective::INVALID;
- }
- const CStack * CBattleInfoEssentials::battleActiveStack() const
- {
- RETURN_IF_NOT_BATTLE(nullptr);
- return battleGetStackByID(getBattle()->activeStack);
- }
- const CStack* CBattleInfoEssentials::battleGetStackByID(int ID, bool onlyAlive) const
- {
- RETURN_IF_NOT_BATTLE(nullptr);
- for(auto s : battleGetAllStacks(true))
- if(s->ID == ID && (!onlyAlive || s->alive()))
- return s;
- return nullptr;
- }
- bool CBattleInfoEssentials::battleDoWeKnowAbout(ui8 side) const
- {
- RETURN_IF_NOT_BATTLE(false);
- auto p = battleGetMySide();
- return p == BattlePerspective::ALL_KNOWING || p == side;
- }
- si8 CBattleInfoEssentials::battleTacticDist() const
- {
- RETURN_IF_NOT_BATTLE(0);
- return getBattle()->tacticDistance;
- }
- si8 CBattleInfoEssentials::battleGetTacticsSide() const
- {
- RETURN_IF_NOT_BATTLE(-1);
- return getBattle()->tacticsSide;
- }
- const CGHeroInstance * CBattleInfoEssentials::battleGetFightingHero(ui8 side) const
- {
- RETURN_IF_NOT_BATTLE(nullptr);
- if(side > 1)
- {
- logGlobal->errorStream() << "FIXME: " << __FUNCTION__ << " wrong argument!";
- return nullptr;
- }
- if(!battleDoWeKnowAbout(side))
- {
- logGlobal->errorStream() << "FIXME: " << __FUNCTION__ << " access check ";
- return nullptr;
- }
- return getBattle()->sides[side].hero;
- }
- const CArmedInstance * CBattleInfoEssentials::battleGetArmyObject(ui8 side) const
- {
- RETURN_IF_NOT_BATTLE(nullptr);
- if(side > 1)
- {
- logGlobal->errorStream() << "FIXME: " << __FUNCTION__ << " wrong argument!";
- return nullptr;
- }
- if(!battleDoWeKnowAbout(side))
- {
- logGlobal->errorStream() << "FIXME: " << __FUNCTION__ << " access check ";
- return nullptr;
- }
- return getBattle()->sides[side].armyObject;
- }
- InfoAboutHero CBattleInfoEssentials::battleGetHeroInfo( ui8 side ) const
- {
- auto hero = getBattle()->sides[side].hero;
- if(!hero)
- {
- logGlobal->warnStream() << __FUNCTION__ << ": side " << (int)side << " does not have hero!";
- return InfoAboutHero();
- }
- return InfoAboutHero(hero, battleDoWeKnowAbout(side));
- }
- int CBattleInfoEssentials::battleCastSpells(ui8 side) const
- {
- RETURN_IF_NOT_BATTLE(-1);
- return getBattle()->sides[side].castSpellsCount;
- }
- ESpellCastProblem::ESpellCastProblem CBattleInfoCallback::battleCanCastSpell(PlayerColor player, ECastingMode::ECastingMode mode) const
- {
- RETURN_IF_NOT_BATTLE(ESpellCastProblem::INVALID);
- const ui8 side = playerToSide(player);
- if(!battleDoWeKnowAbout(side))
- {
- logGlobal->warnStream() << "You can't check if enemy can cast given spell!";
- return ESpellCastProblem::INVALID;
- }
- switch (mode)
- {
- case ECastingMode::HERO_CASTING:
- {
- if(battleTacticDist())
- return ESpellCastProblem::ONGOING_TACTIC_PHASE;
- if(battleCastSpells(side) > 0)
- return ESpellCastProblem::ALREADY_CASTED_THIS_TURN;
- auto hero = battleGetFightingHero(side);
- if(!hero)
- return ESpellCastProblem::NO_HERO_TO_CAST_SPELL;
- if(!hero->getArt(ArtifactPosition::SPELLBOOK))
- return ESpellCastProblem::NO_SPELLBOOK;
- if(hero->hasBonusOfType(Bonus::BLOCK_ALL_MAGIC))
- return ESpellCastProblem::MAGIC_IS_BLOCKED;
- }
- break;
- default:
- break;
- }
- return ESpellCastProblem::OK;
- }
- bool CBattleInfoEssentials::battleCanFlee(PlayerColor player) const
- {
- RETURN_IF_NOT_BATTLE(false);
- ui8 mySide = playerToSide(player);
- const CGHeroInstance *myHero = battleGetFightingHero(mySide);
- //current player have no hero
- if(!myHero)
- return false;
- //eg. one of heroes is wearing shakles of war
- if(myHero->hasBonusOfType(Bonus::BATTLE_NO_FLEEING))
- return false;
- //we are besieged defender
- if(mySide == BattleSide::DEFENDER && battleGetSiegeLevel())
- {
- auto town = battleGetDefendedTown();
- if(!town->hasBuilt(BuildingID::ESCAPE_TUNNEL, ETownType::STRONGHOLD))
- return false;
- }
- return true;
- }
- ui8 CBattleInfoEssentials::playerToSide(PlayerColor player) const
- {
- RETURN_IF_NOT_BATTLE(-1);
- int ret = vstd::find_pos_if(getBattle()->sides, [=](const SideInBattle &side){ return side.color == player; });
- if(ret < 0)
- logGlobal->warnStream() << "Cannot find side for player " << player;
- return ret;
- }
- ui8 CBattleInfoEssentials::battleGetSiegeLevel() const
- {
- RETURN_IF_NOT_BATTLE(0);
- return getBattle()->siege;
- }
- bool CBattleInfoEssentials::battleCanSurrender(PlayerColor player) const
- {
- RETURN_IF_NOT_BATTLE(false);
- //conditions like for fleeing + enemy must have a hero
- return battleCanFlee(player) && battleHasHero(!playerToSide(player));
- }
- bool CBattleInfoEssentials::battleHasHero(ui8 side) const
- {
- RETURN_IF_NOT_BATTLE(false);
- assert(side < 2);
- return getBattle()->sides[side].hero;
- }
- si8 CBattleInfoEssentials::battleGetWallState(int partOfWall) const
- {
- RETURN_IF_NOT_BATTLE(0);
- if(getBattle()->siege == CGTownInstance::NONE)
- return EWallState::NONE;
- assert(partOfWall >= 0 && partOfWall < EWallPart::PARTS_COUNT);
- return getBattle()->si.wallState[partOfWall];
- }
- si8 CBattleInfoCallback::battleHasWallPenalty( const CStack * stack, BattleHex destHex ) const
- {
- return battleHasWallPenalty(stack, stack->position, destHex);
- }
- si8 CBattleInfoCallback::battleHasWallPenalty(const IBonusBearer *bonusBearer, BattleHex shooterPosition, BattleHex destHex) const
- {
- RETURN_IF_NOT_BATTLE(false);
- if (!battleGetSiegeLevel() || bonusBearer->hasBonusOfType(Bonus::NO_WALL_PENALTY))
- return false;
- const int wallInStackLine = lineToWallHex(shooterPosition.getY());
- const int wallInDestLine = lineToWallHex(destHex.getY());
- const bool stackLeft = shooterPosition < wallInStackLine;
- const bool destRight = destHex > wallInDestLine;
- if (stackLeft && destRight) //shooting from outside to inside
- {
- int row = (shooterPosition + destHex) / (2 * GameConstants::BFIELD_WIDTH);
- if (shooterPosition > destHex && ((destHex % GameConstants::BFIELD_WIDTH - shooterPosition % GameConstants::BFIELD_WIDTH) < 2)) //shooting up high
- row -= 2;
- const int wallPos = lineToWallHex(row);
- if (!isWallPartPotentiallyAttackable(battleHexToWallPart(wallPos))) return true;
- }
- return false;
- }
- si8 CBattleInfoCallback::battleCanTeleportTo(const CStack * stack, BattleHex destHex, int telportLevel) const
- {
- RETURN_IF_NOT_BATTLE(false);
- if (!getAccesibility(stack).accessible(destHex, stack))
- return false;
- if (battleGetSiegeLevel() && telportLevel < 2) //check for wall
- return sameSideOfWall(stack->position, destHex);
- return true;
- }
- std::set<BattleHex> CBattleInfoCallback::battleGetAttackedHexes(const CStack* attacker, BattleHex destinationTile, BattleHex attackerPos /*= BattleHex::INVALID*/) const
- {
- std::set<BattleHex> attackedHexes;
- RETURN_IF_NOT_BATTLE(attackedHexes);
- AttackableTiles at = getPotentiallyAttackableHexes(attacker, destinationTile, attackerPos);
- for (BattleHex tile : at.hostileCreaturePositions)
- {
- const CStack * st = battleGetStackByPos(tile, true);
- if(st && st->owner != attacker->owner) //only hostile stacks - does it work well with Berserk?
- {
- attackedHexes.insert(tile);
- }
- }
- for (BattleHex tile : at.friendlyCreaturePositions)
- {
- if(battleGetStackByPos(tile, true)) //friendly stacks can also be damaged by Dragon Breath
- {
- attackedHexes.insert(tile);
- }
- }
- return attackedHexes;
- }
- SpellID CBattleInfoCallback::battleGetRandomStackSpell(const CStack * stack, ERandomSpell mode) const
- {
- switch (mode)
- {
- case RANDOM_GENIE:
- return getRandomBeneficialSpell(stack); //target
- break;
- case RANDOM_AIMED:
- return getRandomCastedSpell(stack); //caster
- break;
- default:
- logGlobal->errorStream() << "Incorrect mode of battleGetRandomSpell (" << mode <<")";
- return SpellID::NONE;
- }
- }
- const CStack* CBattleInfoCallback::battleGetStackByPos(BattleHex pos, bool onlyAlive) const
- {
- RETURN_IF_NOT_BATTLE(nullptr);
- for(auto s : battleGetAllStacks(true))
- if(vstd::contains(s->getHexes(), pos) && (!onlyAlive || s->alive()))
- return s;
- return nullptr;
- }
- void CBattleInfoCallback::battleGetStackQueue(std::vector<const CStack *> &out, const int howMany, const int turn /*= 0*/, int lastMoved /*= -1*/) const
- {
- RETURN_IF_NOT_BATTLE();
- //let's define a huge lambda
- auto takeStack = [&](std::vector<const CStack *> &st) -> const CStack*
- {
- const CStack *ret = nullptr;
- unsigned i, //fastest stack
- j=0; //fastest stack of the other side
- for(i = 0; i < st.size(); i++)
- if(st[i])
- break;
- //no stacks left
- if(i == st.size())
- return nullptr;
- const CStack *fastest = st[i], *other = nullptr;
- int bestSpeed = fastest->Speed(turn);
- //FIXME: comparison between bool and integer. Logic does not makes sense either
- if(fastest->attackerOwned != lastMoved)
- {
- ret = fastest;
- }
- else
- {
- for(j = i + 1; j < st.size(); j++)
- {
- if(!st[j]) continue;
- if(st[j]->attackerOwned != lastMoved || st[j]->Speed(turn) != bestSpeed)
- break;
- }
- if(j >= st.size())
- {
- ret = fastest;
- }
- else
- {
- other = st[j];
- if(other->Speed(turn) != bestSpeed)
- ret = fastest;
- else
- ret = other;
- }
- }
- assert(ret);
- if(ret == fastest)
- st[i] = nullptr;
- else
- st[j] = nullptr;
- lastMoved = ret->attackerOwned;
- return ret;
- };
- //We'll split creatures with remaining movement to 4 buckets
- // [0] - turrets/catapult,
- // [1] - normal (unmoved) creatures, other war machines,
- // [2] - waited cres that had morale,
- // [3] - rest of waited cres
- std::vector<const CStack *> phase[4];
- int toMove = 0; //how many stacks still has move
- const CStack *active = battleActiveStack();
- //active stack hasn't taken any action yet - must be placed at the beginning of queue, no matter what
- if(!turn && active && active->willMove() && !active->waited())
- {
- out.push_back(active);
- if(out.size() == howMany)
- return;
- }
- auto allStacks = battleGetAllStacks(true);
- if(!vstd::contains_if(allStacks, [](const CStack *stack) { return stack->willMove(100000); })) //little evil, but 100000 should be enough for all effects to disappear
- {
- //No stack will be able to move, battle is over.
- out.clear();
- return;
- }
- for(auto s : battleGetAllStacks(true))
- {
- if((turn <= 0 && !s->willMove()) //we are considering current round and stack won't move
- || (turn > 0 && !s->canMove(turn)) //stack won't be able to move in later rounds
- || (turn <= 0 && s == active && out.size() && s == out.front())) //it's active stack already added at the beginning of queue
- {
- continue;
- }
- int p = -1; //in which phase this tack will move?
- if(turn <= 0 && s->waited()) //consider waiting state only for ongoing round
- {
- if(vstd::contains(s->state, EBattleStackState::HAD_MORALE))
- p = 2;
- else
- p = 3;
- }
- else if(s->getCreature()->idNumber == CreatureID::CATAPULT || s->getCreature()->idNumber == CreatureID::ARROW_TOWERS) //catapult and turrets are first
- {
- p = 0;
- }
- else
- {
- p = 1;
- }
- phase[p].push_back(s);
- toMove++;
- }
- for(int i = 0; i < 4; i++)
- boost::sort(phase[i], CMP_stack(i, turn > 0 ? turn : 0));
- for(size_t i = 0; i < phase[0].size() && i < howMany; i++)
- out.push_back(phase[0][i]);
- if(out.size() == howMany)
- return;
- if(lastMoved == -1)
- {
- if(active)
- {
- //FIXME: both branches contain same code!!!
- if(out.size() && out.front() == active)
- lastMoved = active->attackerOwned;
- else
- lastMoved = active->attackerOwned;
- }
- else
- {
- lastMoved = 0;
- }
- }
- int pi = 1;
- while(out.size() < howMany)
- {
- const CStack *hlp = takeStack(phase[pi]);
- if(!hlp)
- {
- pi++;
- if(pi > 3)
- {
- //if(turn != 2)
- battleGetStackQueue(out, howMany, turn + 1, lastMoved);
- return;
- }
- }
- else
- {
- out.push_back(hlp);
- }
- }
- }
- void CBattleInfoCallback::battleGetStackCountOutsideHexes(bool *ac) const
- {
- RETURN_IF_NOT_BATTLE();
- auto accessibility = getAccesibility();
- for(int i = 0; i < accessibility.size(); i++)
- ac[i] = (accessibility[i] == EAccessibility::ACCESSIBLE);
- }
- std::vector<BattleHex> CBattleInfoCallback::battleGetAvailableHexes(const CStack * stack, bool addOccupiable, std::vector<BattleHex> * attackable) const
- {
- std::vector<BattleHex> ret;
- RETURN_IF_NOT_BATTLE(ret);
- if(!stack->position.isValid()) //turrets
- return ret;
- auto reachability = getReachability(stack);
- for (int i = 0; i < GameConstants::BFIELD_SIZE; ++i)
- {
- // If obstacles or other stacks makes movement impossible, it can't be helped.
- if(!reachability.isReachable(i))
- continue;
- if(battleTacticDist() && battleGetTacticsSide() == !stack->attackerOwned)
- {
- //Stack has to perform tactic-phase movement -> can enter any reachable tile within given range
- if(!isInTacticRange(i))
- continue;
- }
- else
- {
- //Not tactics phase -> destination must be reachable and within stack range.
- if(reachability.distances[i] > stack->Speed(0, true))
- continue;
- }
- ret.push_back(i);
- if(addOccupiable && stack->doubleWide())
- {
- //If two-hex stack can stand on hex i then obviously it can occupy its second hex from that position
- ret.push_back(stack->occupiedHex(i));
- }
- }
- if(attackable)
- {
- auto meleeAttackable = [&](BattleHex hex) -> bool
- {
- // Return true if given hex has at least one available neighbour.
- // Available hexes are already present in ret vector.
- auto availableNeighbor = boost::find_if(ret, [=] (BattleHex availableHex)
- { return BattleHex::mutualPosition(hex, availableHex) >= 0; });
- return availableNeighbor != ret.end();
- };
- for(const CStack * otherSt : battleAliveStacks(stack->attackerOwned))
- {
- if(!otherSt->isValidTarget(false))
- continue;
- std::vector<BattleHex> occupied = otherSt->getHexes();
- if(battleCanShoot(stack, otherSt->position))
- {
- attackable->insert(attackable->end(), occupied.begin(), occupied.end());
- continue;
- }
- for(BattleHex he : occupied)
- {
- if(meleeAttackable(he))
- attackable->push_back(he);
- }
- }
- }
- //adding occupiable likely adds duplicates to ret -> clean it up
- boost::sort(ret);
- ret.erase(boost::unique(ret).end(), ret.end());
- return ret;
- }
- bool CBattleInfoCallback::battleCanShoot(const CStack * stack, BattleHex dest) const
- {
- RETURN_IF_NOT_BATTLE(false);
- if(battleTacticDist()) //no shooting during tactics
- return false;
- const CStack *dst = battleGetStackByPos(dest);
- if(!stack || !dst)
- return false;
- if(stack->hasBonusOfType(Bonus::FORGETFULL)) //forgetfulness
- return false;
- if(stack->getCreature()->idNumber == CreatureID::CATAPULT && dst) //catapult cannot attack creatures
- return false;
- //const CGHeroInstance * stackHero = battleGetOwner(stack);
- if(stack->hasBonusOfType(Bonus::SHOOTER)//it's shooter
- && stack->owner != dst->owner
- && dst->alive()
- && (!battleIsStackBlocked(stack) || stack->hasBonusOfType(Bonus::FREE_SHOOTING))
- && stack->shots
- )
- return true;
- return false;
- }
- TDmgRange CBattleInfoCallback::calculateDmgRange(const CStack* attacker, const CStack* defender, bool shooting,
- ui8 charge, bool lucky, bool unlucky, bool deathBlow, bool ballistaDoubleDmg) const
- {
- return calculateDmgRange(attacker, defender, attacker->count, shooting, charge, lucky, unlucky, deathBlow, ballistaDoubleDmg);
- }
- TDmgRange CBattleInfoCallback::calculateDmgRange(const BattleAttackInfo &info) const
- {
- auto battleBonusValue = [&](const IBonusBearer * bearer, CSelector selector) -> int
- {
- auto noLimit = Selector::effectRange(Bonus::NO_LIMIT);
- auto limitMatches = info.shooting
- ? Selector::effectRange(Bonus::ONLY_DISTANCE_FIGHT)
- : Selector::effectRange(Bonus::ONLY_MELEE_FIGHT);
- //any regular bonuses or just ones for melee/ranged
- return bearer->getBonuses(selector, noLimit.Or(limitMatches))->totalValue();
- };
- double additiveBonus = 1.0, multBonus = 1.0,
- minDmg = info.attackerBonuses->getMinDamage() * info.attackerCount,//TODO: ONLY_MELEE_FIGHT / ONLY_DISTANCE_FIGHT
- maxDmg = info.attackerBonuses->getMaxDamage() * info.attackerCount;
- const CCreature *attackerType = info.attacker->getCreature(),
- *defenderType = info.defender->getCreature();
- if(attackerType->idNumber == CreatureID::ARROW_TOWERS)
- {
- SiegeStuffThatShouldBeMovedToHandlers::retreiveTurretDamageRange(battleGetDefendedTown(), info.attacker, minDmg, maxDmg);
- }
- if(info.attackerBonuses->hasBonusOfType(Bonus::SIEGE_WEAPON) && attackerType->idNumber != CreatureID::ARROW_TOWERS) //any siege weapon, but only ballista can attack (second condition - not arrow turret)
- { //minDmg and maxDmg are multiplied by hero attack + 1
- auto retreiveHeroPrimSkill = [&](int skill) -> int
- {
- const Bonus *b = info.attackerBonuses->getBonus(Selector::sourceTypeSel(Bonus::HERO_BASE_SKILL).And(Selector::typeSubtype(Bonus::PRIMARY_SKILL, skill)));
- return b ? b->val : 0; //if there is no hero or no info on his primary skill, return 0
- };
- minDmg *= retreiveHeroPrimSkill(PrimarySkill::ATTACK) + 1;
- maxDmg *= retreiveHeroPrimSkill(PrimarySkill::ATTACK) + 1;
- }
- int attackDefenceDifference = 0;
- double multAttackReduction = (100 - battleBonusValue (info.attackerBonuses, Selector::type(Bonus::GENERAL_ATTACK_REDUCTION))) / 100.0;
- attackDefenceDifference += battleBonusValue (info.attackerBonuses, Selector::typeSubtype(Bonus::PRIMARY_SKILL, PrimarySkill::ATTACK)) * multAttackReduction;
- double multDefenceReduction = (100 - battleBonusValue (info.attackerBonuses, Selector::type(Bonus::ENEMY_DEFENCE_REDUCTION))) / 100.0;
- attackDefenceDifference -= info.defenderBonuses->Defense() * multDefenceReduction;
- if(const Bonus *slayerEffect = info.attackerBonuses->getEffect(SpellID::SLAYER)) //slayer handling //TODO: apply only ONLY_MELEE_FIGHT / DISTANCE_FIGHT?
- {
- std::vector<int> affectedIds;
- int spLevel = slayerEffect->val;
- for(int g = 0; g < VLC->creh->creatures.size(); ++g)
- {
- for(const Bonus *b : VLC->creh->creatures[g]->getBonusList())
- {
- if ( (b->type == Bonus::KING3 && spLevel >= 3) || //expert
- (b->type == Bonus::KING2 && spLevel >= 2) || //adv +
- (b->type == Bonus::KING1 && spLevel >= 0) ) //none or basic +
- {
- affectedIds.push_back(g);
- break;
- }
- }
- }
- for(auto & affectedId : affectedIds)
- {
- if(defenderType->idNumber == affectedId)
- {
- attackDefenceDifference += SpellID(SpellID::SLAYER).toSpell()->getPower(spLevel);
- break;
- }
- }
- }
- //bonus from attack/defense skills
- if(attackDefenceDifference < 0) //decreasing dmg
- {
- const double dec = std::min(0.025 * (-attackDefenceDifference), 0.7);
- multBonus *= 1.0 - dec;
- }
- else //increasing dmg
- {
- const double inc = std::min(0.05 * attackDefenceDifference, 4.0);
- additiveBonus += inc;
- }
- //applying jousting bonus
- if( info.attackerBonuses->hasBonusOfType(Bonus::JOUSTING) && !info.defenderBonuses->hasBonusOfType(Bonus::CHARGE_IMMUNITY) )
- additiveBonus += info.chargedFields * 0.05;
- //handling secondary abilities and artifacts giving premies to them
- if(info.shooting)
- additiveBonus += info.attackerBonuses->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::ARCHERY) / 100.0;
- else
- additiveBonus += info.attackerBonuses->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::OFFENCE) / 100.0;
- if(info.defenderBonuses)
- multBonus *= (std::max(0, 100 - info.defenderBonuses->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::ARMORER))) / 100.0;
- //handling hate effect
- additiveBonus += info.attackerBonuses->valOfBonuses(Bonus::HATE, defenderType->idNumber.toEnum()) / 100.;
- //luck bonus
- if (info.luckyHit)
- {
- additiveBonus += 1.0;
- }
- //unlucky hit, used only if negative luck is enabled
- if (info.unluckyHit)
- {
- additiveBonus -= 0.5; // FIXME: how bad (and luck in general) should work with following bonuses?
- }
- //ballista double dmg
- if(info.ballistaDoubleDamage)
- {
- additiveBonus += 1.0;
- }
- if (info.deathBlow) //Dread Knight and many WoGified creatures
- {
- additiveBonus += 1.0;
- }
- //handling spell effects
- if(!info.shooting) //eg. shield
- {
- multBonus *= (100 - info.defenderBonuses->valOfBonuses(Bonus::GENERAL_DAMAGE_REDUCTION, 0)) / 100.0;
- }
- else if(info.shooting) //eg. air shield
- {
- multBonus *= (100 - info.defenderBonuses->valOfBonuses(Bonus::GENERAL_DAMAGE_REDUCTION, 1)) / 100.0;
- }
- TBonusListPtr curseEffects = info.attackerBonuses->getBonuses(Selector::type(Bonus::ALWAYS_MINIMUM_DAMAGE));
- TBonusListPtr blessEffects = info.attackerBonuses->getBonuses(Selector::type(Bonus::ALWAYS_MAXIMUM_DAMAGE));
- int curseBlessAdditiveModifier = blessEffects->totalValue() - curseEffects->totalValue();
- double curseMultiplicativePenalty = curseEffects->size() ? (*std::max_element(curseEffects->begin(), curseEffects->end(), &Bonus::compareByAdditionalInfo))->additionalInfo : 0;
- if(curseMultiplicativePenalty) //curse handling (partial, the rest is below)
- {
- multBonus *= 1.0 - curseMultiplicativePenalty/100;
- }
- auto isAdvancedAirShield = [](const Bonus *bonus)
- {
- return bonus->source == Bonus::SPELL_EFFECT
- && bonus->sid == SpellID::AIR_SHIELD
- && bonus->val >= SecSkillLevel::ADVANCED;
- };
- //wall / distance penalty + advanced air shield
- const bool distPenalty = !info.attackerBonuses->hasBonusOfType(Bonus::NO_DISTANCE_PENALTY) && battleHasDistancePenalty(info.attackerBonuses, info.attackerPosition, info.defenderPosition);
- const bool obstaclePenalty = battleHasWallPenalty(info.attackerBonuses, info.attackerPosition, info.defenderPosition);
- if (info.shooting)
- {
- if (distPenalty || info.defenderBonuses->hasBonus(isAdvancedAirShield))
- {
- multBonus *= 0.5;
- }
- if (obstaclePenalty)
- {
- multBonus *= 0.5; //cumulative
- }
- }
- if(!info.shooting && info.attackerBonuses->hasBonusOfType(Bonus::SHOOTER) && !info.attackerBonuses->hasBonusOfType(Bonus::NO_MELEE_PENALTY))
- {
- multBonus *= 0.5;
- }
- // TODO attack on petrified unit 50%
- // psychic elementals versus mind immune units 50%
- // blinded unit retaliates
- minDmg *= additiveBonus * multBonus;
- maxDmg *= additiveBonus * multBonus;
- TDmgRange returnedVal;
- if(curseEffects->size()) //curse handling (rest)
- {
- minDmg += curseBlessAdditiveModifier;
- returnedVal = std::make_pair(int(minDmg), int(minDmg));
- }
- else if(blessEffects->size()) //bless handling
- {
- maxDmg += curseBlessAdditiveModifier;
- returnedVal = std::make_pair(int(maxDmg), int(maxDmg));
- }
- else
- {
- returnedVal = std::make_pair(int(minDmg), int(maxDmg));
- }
- //damage cannot be less than 1
- vstd::amax(returnedVal.first, 1);
- vstd::amax(returnedVal.second, 1);
- return returnedVal;
- }
- TDmgRange CBattleInfoCallback::calculateDmgRange( const CStack* attacker, const CStack* defender, TQuantity attackerCount,
- bool shooting, ui8 charge, bool lucky, bool unlucky, bool deathBlow, bool ballistaDoubleDmg ) const
- {
- BattleAttackInfo bai(attacker, defender, shooting);
- bai.attackerCount = attackerCount;
- bai.chargedFields = charge;
- bai.luckyHit = lucky;
- bai.unluckyHit = unlucky;
- bai.deathBlow = deathBlow;
- bai.ballistaDoubleDamage = ballistaDoubleDmg;
- return calculateDmgRange(bai);
- }
- TDmgRange CBattleInfoCallback::battleEstimateDamage(const CStack * attacker, const CStack * defender, TDmgRange * retaliationDmg) const
- {
- RETURN_IF_NOT_BATTLE(std::make_pair(0, 0));
- const bool shooting = battleCanShoot(attacker, defender->position);
- const BattleAttackInfo bai(attacker, defender, shooting);
- return battleEstimateDamage(bai, retaliationDmg);
- }
- std::pair<ui32, ui32> CBattleInfoCallback::battleEstimateDamage(const BattleAttackInfo &bai, std::pair<ui32, ui32> * retaliationDmg /*= nullptr*/) const
- {
- RETURN_IF_NOT_BATTLE(std::make_pair(0, 0));
- //const bool shooting = battleCanShoot(bai.attacker, bai.defenderPosition); //TODO handle bonus bearer
- //const ui8 mySide = !attacker->attackerOwned;
- TDmgRange ret = calculateDmgRange(bai);
- if(retaliationDmg)
- {
- if(bai.shooting)
- {
- retaliationDmg->first = retaliationDmg->second = 0;
- }
- else
- {
- ui32 TDmgRange::* pairElems[] = {&TDmgRange::first, &TDmgRange::second};
- for (int i=0; i<2; ++i)
- {
- BattleStackAttacked bsa;
- bsa.damageAmount = ret.*pairElems[i];
- bai.defender->prepareAttacked(bsa, gs->getRandomGenerator(), bai.defenderCount);
- auto retaliationAttack = bai.reverse();
- retaliationAttack.attackerCount = bsa.newAmount;
- retaliationDmg->*pairElems[!i] = calculateDmgRange(retaliationAttack).*pairElems[!i];
- }
- }
- }
- return ret;
- }
- shared_ptr<const CObstacleInstance> CBattleInfoCallback::battleGetObstacleOnPos(BattleHex tile, bool onlyBlocking /*= true*/) const
- {
- RETURN_IF_NOT_BATTLE(shared_ptr<const CObstacleInstance>());
- for(auto &obs : battleGetAllObstacles())
- {
- if(vstd::contains(obs->getBlockedTiles(), tile)
- || (!onlyBlocking && vstd::contains(obs->getAffectedTiles(), tile)))
- {
- return obs;
- }
- }
- return shared_ptr<const CObstacleInstance>();
- }
- AccessibilityInfo CBattleInfoCallback::getAccesibility() const
- {
- AccessibilityInfo ret;
- ret.fill(EAccessibility::ACCESSIBLE);
- //removing accessibility for side columns of hexes
- for(int y = 0; y < GameConstants::BFIELD_HEIGHT; y++)
- {
- ret[BattleHex(GameConstants::BFIELD_WIDTH - 1, y)] = EAccessibility::SIDE_COLUMN;
- ret[BattleHex(0, y)] = EAccessibility::SIDE_COLUMN;
- }
- //gate -> should be before stacks
- if(battleGetSiegeLevel() > 0 && battleGetWallState(EWallPart::GATE) != EWallState::DESTROYED)
- {
- ret[95] = ret[96] = EAccessibility::GATE; //block gate's hexes
- }
- //tiles occupied by standing stacks
- for(auto stack : battleAliveStacks())
- {
- for(auto hex : stack->getHexes())
- if(hex.isAvailable()) //towers can have <0 pos; we don't also want to overwrite side columns
- ret[hex] = EAccessibility::ALIVE_STACK;
- }
- //obstacles
- for(const auto &obst : battleGetAllObstacles())
- {
- for(auto hex : obst->getBlockedTiles())
- ret[hex] = EAccessibility::OBSTACLE;
- }
- //walls
- if(battleGetSiegeLevel() > 0)
- {
- static const int permanentlyLocked[] = {12, 45, 78, 112, 147, 165};
- for(auto hex : permanentlyLocked)
- ret[hex] = EAccessibility::UNAVAILABLE;
- //TODO likely duplicated logic
- static const std::pair<int, BattleHex> lockedIfNotDestroyed[] = //(which part of wall, which hex is blocked if this part of wall is not destroyed
- {std::make_pair(2, BattleHex(182)), std::make_pair(3, BattleHex(130)),
- std::make_pair(4, BattleHex(62)), std::make_pair(5, BattleHex(29))};
- for(auto & elem : lockedIfNotDestroyed)
- {
- if(battleGetWallState(elem.first) != EWallState::DESTROYED)
- ret[elem.second] = EAccessibility::DESTRUCTIBLE_WALL;
- }
- }
- return ret;
- }
- AccessibilityInfo CBattleInfoCallback::getAccesibility(const CStack *stack) const
- {
- return getAccesibility(stack->getHexes());
- }
- AccessibilityInfo CBattleInfoCallback::getAccesibility(const std::vector<BattleHex> &accessibleHexes) const
- {
- auto ret = getAccesibility();
- for(auto hex : accessibleHexes)
- if(hex.isValid())
- ret[hex] = EAccessibility::ACCESSIBLE;
- return ret;
- }
- ReachabilityInfo CBattleInfoCallback::makeBFS(const AccessibilityInfo &accessibility, const ReachabilityInfo::Parameters ¶ms) const
- {
- ReachabilityInfo ret;
- ret.accessibility = accessibility;
- ret.params = params;
- ret.predecessors.fill(BattleHex::INVALID);
- ret.distances.fill(ReachabilityInfo::INFINITE_DIST);
- if(!params.startPosition.isValid()) //if got call for arrow turrets
- return ret;
- const std::set<BattleHex> quicksands = getStoppers(params.perspective);
- //const bool twoHexCreature = params.doubleWide;
- std::queue<BattleHex> hexq; //bfs queue
- //first element
- hexq.push(params.startPosition);
- ret.distances[params.startPosition] = 0;
- while(!hexq.empty()) //bfs loop
- {
- const BattleHex curHex = hexq.front();
- hexq.pop();
- //walking stack can't step past the quicksands
- //TODO what if second hex of two-hex creature enters quicksand
- if(curHex != params.startPosition && vstd::contains(quicksands, curHex))
- continue;
- const int costToNeighbour = ret.distances[curHex] + 1;
- for(BattleHex neighbour : curHex.neighbouringTiles())
- {
- const bool accessible = accessibility.accessible(neighbour, params.doubleWide, params.attackerOwned);
- const int costFoundSoFar = ret.distances[neighbour];
- if(accessible && costToNeighbour < costFoundSoFar)
- {
- hexq.push(neighbour);
- ret.distances[neighbour] = costToNeighbour;
- ret.predecessors[neighbour] = curHex;
- }
- }
- }
- return ret;
- }
- ReachabilityInfo CBattleInfoCallback::makeBFS(const CStack *stack) const
- {
- return makeBFS(getAccesibility(stack), ReachabilityInfo::Parameters(stack));
- }
- std::set<BattleHex> CBattleInfoCallback::getStoppers(BattlePerspective::BattlePerspective whichSidePerspective) const
- {
- std::set<BattleHex> ret;
- RETURN_IF_NOT_BATTLE(ret);
- for(auto &oi : battleGetAllObstacles(whichSidePerspective))
- {
- if(battleIsObstacleVisibleForSide(*oi, whichSidePerspective))
- {
- range::copy(oi->getStoppingTile(), vstd::set_inserter(ret));
- }
- }
- return ret;
- }
- std::pair<const CStack *, BattleHex> CBattleInfoCallback::getNearestStack(const CStack * closest, boost::logic::tribool attackerOwned) const
- {
- auto reachability = getReachability(closest);
- // I hate std::pairs with their undescriptive member names first / second
- struct DistStack
- {
- int distanceToPred;
- const CStack *stack;
- };
- std::vector<DistStack> stackPairs; //pairs <<distance, hex>, stack>
- for(int g=0; g<GameConstants::BFIELD_SIZE; ++g)
- {
- const CStack * atG = battleGetStackByPos(g);
- if(!atG || atG->ID == closest->ID) //if there is no stack or we are the closest one
- continue;
- if(boost::logic::indeterminate(attackerOwned) || atG->attackerOwned == attackerOwned)
- {
- if (reachability.isReachable(g))
- //FIXME: hexes occupied by enemy stack are not accessible. Need to use BattleInfo::getPath or similar
- {
- DistStack hlp = {reachability.distances[reachability.predecessors[g]], atG};
- stackPairs.push_back(hlp);
- }
- }
- }
- if (stackPairs.size())
- {
- auto comparator = [](DistStack lhs, DistStack rhs) { return lhs.distanceToPred < rhs.distanceToPred; };
- auto minimal = boost::min_element(stackPairs, comparator);
- return std::make_pair(minimal->stack, reachability.predecessors[minimal->stack->position]);
- }
- else
- return std::make_pair<const CStack * , BattleHex>(nullptr, BattleHex::INVALID);
- }
- si8 CBattleInfoCallback::battleGetTacticDist() const
- {
- RETURN_IF_NOT_BATTLE(0);
- //TODO get rid of this method
- if(battleDoWeKnowAbout(battleGetTacticsSide()))
- return battleTacticDist();
- return 0;
- }
- bool CBattleInfoCallback::isInTacticRange(BattleHex dest) const
- {
- RETURN_IF_NOT_BATTLE(false);
- auto side = battleGetTacticsSide();
- auto dist = battleGetTacticDist();
- return ((!side && dest.getX() > 0 && dest.getX() <= dist)
- || (side && dest.getX() < GameConstants::BFIELD_WIDTH - 1 && dest.getX() >= GameConstants::BFIELD_WIDTH - dist - 1));
- }
- ReachabilityInfo CBattleInfoCallback::getReachability(const CStack *stack) const
- {
- ReachabilityInfo::Parameters params(stack);
- if(!battleDoWeKnowAbout(!stack->attackerOwned))
- {
- //Stack is held by enemy, we can't use his perspective to check for reachability.
- // Happens ie. when hovering enemy stack for its range. The arg could be set properly, but it's easier to fix it here.
- params.perspective = battleGetMySide();
- }
- return getReachability(params);
- }
- ReachabilityInfo CBattleInfoCallback::getReachability(const ReachabilityInfo::Parameters ¶ms) const
- {
- if(params.flying)
- return getFlyingReachability(params);
- else
- return makeBFS(getAccesibility(params.knownAccessible), params);
- }
- ReachabilityInfo CBattleInfoCallback::getFlyingReachability(const ReachabilityInfo::Parameters ¶ms) const
- {
- ReachabilityInfo ret;
- ret.accessibility = getAccesibility(params.knownAccessible);
- for(int i = 0; i < GameConstants::BFIELD_SIZE; i++)
- {
- if(ret.accessibility.accessible(i, params.doubleWide, params.attackerOwned))
- {
- ret.predecessors[i] = params.startPosition;
- ret.distances[i] = BattleHex::getDistance(params.startPosition, i);
- }
- }
- return ret;
- }
- AttackableTiles CBattleInfoCallback::getPotentiallyAttackableHexes (const CStack* attacker, BattleHex destinationTile, BattleHex attackerPos) const
- {
- //does not return hex attacked directly
- //TODO: apply rotation to two-hex attackers
- bool isAttacker = attacker->attackerOwned;
- AttackableTiles at;
- RETURN_IF_NOT_BATTLE(at);
- const int WN = GameConstants::BFIELD_WIDTH;
- ui16 hex = (attackerPos != BattleHex::INVALID) ? attackerPos.hex : attacker->position.hex; //real or hypothetical (cursor) position
- //FIXME: dragons or cerbers can rotate before attack, making their base hex different (#1124)
- bool reverse = isToReverse (hex, destinationTile, isAttacker, attacker->doubleWide(), isAttacker);
- if (reverse)
- {
- hex = attacker->occupiedHex(hex); //the other hex stack stands on
- }
- if (attacker->hasBonusOfType(Bonus::ATTACKS_ALL_ADJACENT))
- {
- boost::copy (attacker->getSurroundingHexes (attackerPos), vstd::set_inserter (at.hostileCreaturePositions));
- }
- if (attacker->hasBonusOfType(Bonus::THREE_HEADED_ATTACK))
- {
- std::vector<BattleHex> hexes = attacker->getSurroundingHexes(attackerPos);
- for (BattleHex tile : hexes)
- {
- if ((BattleHex::mutualPosition(tile, destinationTile) > -1 && BattleHex::mutualPosition (tile, hex) > -1)) //adjacent both to attacker's head and attacked tile
- {
- const CStack * st = battleGetStackByPos(tile, true);
- if(st && st->owner != attacker->owner) //only hostile stacks - does it work well with Berserk?
- {
- at.hostileCreaturePositions.insert(tile);
- }
- }
- }
- }
- if (attacker->hasBonusOfType(Bonus::TWO_HEX_ATTACK_BREATH) && BattleHex::mutualPosition (destinationTile.hex, hex) > -1) //only adjacent hexes are subject of dragon breath calculation
- {
- std::vector<BattleHex> hexes; //only one, in fact
- int pseudoVector = destinationTile.hex - hex;
- switch (pseudoVector)
- {
- case 1:
- case -1:
- BattleHex::checkAndPush (destinationTile.hex + pseudoVector, hexes);
- break;
- case WN: //17 //left-down or right-down
- case -WN: //-17 //left-up or right-up
- case WN + 1: //18 //right-down
- case -WN + 1: //-16 //right-up
- BattleHex::checkAndPush (destinationTile.hex + pseudoVector + ((hex/WN)%2 ? 1 : -1 ), hexes);
- break;
- case WN-1: //16 //left-down
- case -WN-1: //-18 //left-up
- BattleHex::checkAndPush (destinationTile.hex + pseudoVector + ((hex/WN)%2 ? 1 : 0), hexes);
- break;
- }
- for (BattleHex tile : hexes)
- {
- //friendly stacks can also be damaged by Dragon Breath
- if (battleGetStackByPos (tile, true))
- at.friendlyCreaturePositions.insert (tile);
- }
- }
- return at;
- }
- std::set<const CStack*> CBattleInfoCallback::getAttackedCreatures(const CStack* attacker, BattleHex destinationTile, BattleHex attackerPos /*= BattleHex::INVALID*/) const
- {
- std::set<const CStack*> attackedCres;
- RETURN_IF_NOT_BATTLE(attackedCres);
- AttackableTiles at = getPotentiallyAttackableHexes(attacker, destinationTile, attackerPos);
- for (BattleHex tile : at.hostileCreaturePositions) //all around & three-headed attack
- {
- const CStack * st = battleGetStackByPos(tile, true);
- if(st && st->owner != attacker->owner) //only hostile stacks - does it work well with Berserk?
- {
- attackedCres.insert(st);
- }
- }
- for (BattleHex tile : at.friendlyCreaturePositions)
- {
- const CStack * st = battleGetStackByPos(tile, true);
- if(st) //friendly stacks can also be damaged by Dragon Breath
- {
- attackedCres.insert(st);
- }
- }
- return attackedCres;
- }
- //TODO: this should apply also to mechanics and cursor interface
- bool CBattleInfoCallback::isToReverseHlp (BattleHex hexFrom, BattleHex hexTo, bool curDir) const
- {
- int fromX = hexFrom.getX();
- int fromY = hexFrom.getY();
- int toX = hexTo.getX();
- int toY = hexTo.getY();
- if (curDir) // attacker, facing right
- {
- if (fromX < toX)
- return false;
- if (fromX > toX)
- return true;
- if (fromY % 2 == 0 && toY % 2 == 1)
- return true;
- return false;
- }
- else // defender, facing left
- {
- if(fromX < toX)
- return true;
- if(fromX > toX)
- return false;
- if (fromY % 2 == 1 && toY % 2 == 0)
- return true;
- return false;
- }
- }
- //TODO: this should apply also to mechanics and cursor interface
- bool CBattleInfoCallback::isToReverse (BattleHex hexFrom, BattleHex hexTo, bool curDir, bool toDoubleWide, bool toDir) const
- {
- if (hexTo < 0 || hexFrom < 0) //turret
- return false;
- if (toDoubleWide)
- {
- return (isToReverseHlp (hexFrom, hexTo, curDir)) &&
- (toDir ? isToReverseHlp (hexFrom, hexTo-1, curDir) : isToReverseHlp (hexFrom, hexTo+1, curDir));
- }
- else
- {
- return isToReverseHlp(hexFrom, hexTo, curDir);
- }
- }
- ReachabilityInfo::TDistances CBattleInfoCallback::battleGetDistances(const CStack * stack, BattleHex hex /*= BattleHex::INVALID*/, BattleHex * predecessors /*= nullptr*/) const
- {
- ReachabilityInfo::TDistances ret;
- ret.fill(-1);
- RETURN_IF_NOT_BATTLE(ret);
- ReachabilityInfo::Parameters params(stack);
- params.perspective = battleGetMySide();
- params.startPosition = hex.isValid() ? hex : stack->position;
- auto reachability = getReachability(params);
- boost::copy(reachability.distances, ret.begin());
- if(predecessors)
- for(int i = 0; i < GameConstants::BFIELD_SIZE; i++)
- predecessors[i] = reachability.predecessors[i];
- return ret;
- }
- si8 CBattleInfoCallback::battleHasDistancePenalty(const CStack * stack, BattleHex destHex) const
- {
- return battleHasDistancePenalty(stack, stack->position, destHex);
- }
- si8 CBattleInfoCallback::battleHasDistancePenalty(const IBonusBearer *bonusBearer, BattleHex shooterPosition, BattleHex destHex) const
- {
- RETURN_IF_NOT_BATTLE(false);
- if(bonusBearer->hasBonusOfType(Bonus::NO_DISTANCE_PENALTY))
- return false;
- if(const CStack * dstStack = battleGetStackByPos(destHex, false))
- {
- //If any hex of target creature is within range, there is no penalty
- for(auto hex : dstStack->getHexes())
- if(BattleHex::getDistance(shooterPosition, hex) <= GameConstants::BATTLE_PENALTY_DISTANCE)
- return false;
- //TODO what about two-hex shooters?
- }
- else
- {
- if (BattleHex::getDistance(shooterPosition, destHex) <= GameConstants::BATTLE_PENALTY_DISTANCE)
- return false;
- }
- return true;
- }
- BattleHex CBattleInfoCallback::wallPartToBattleHex(EWallPart::EWallPart part) const
- {
- RETURN_IF_NOT_BATTLE(BattleHex::INVALID);
- return WallPartToHex(part);
- }
- EWallPart::EWallPart CBattleInfoCallback::battleHexToWallPart(BattleHex hex) const
- {
- RETURN_IF_NOT_BATTLE(EWallPart::INVALID);
- return hexToWallPart(hex);
- }
- bool CBattleInfoCallback::isWallPartPotentiallyAttackable(EWallPart::EWallPart wallPart) const
- {
- RETURN_IF_NOT_BATTLE(false);
- return wallPart != EWallPart::INDESTRUCTIBLE_PART && wallPart != EWallPart::INDESTRUCTIBLE_PART_OF_GATE &&
- wallPart != EWallPart::INVALID;
- }
- std::vector<BattleHex> CBattleInfoCallback::getAttackableBattleHexes() const
- {
- std::vector<BattleHex> attackableBattleHexes;
- RETURN_IF_NOT_BATTLE(attackableBattleHexes);
- for(auto & wallPartPair : wallParts)
- {
- if(isWallPartPotentiallyAttackable(wallPartPair.second))
- {
- auto wallState = static_cast<EWallState::EWallState>(battleGetWallState(static_cast<int>(wallPartPair.second)));
- if(wallState == EWallState::INTACT || wallState == EWallState::DAMAGED)
- {
- attackableBattleHexes.push_back(BattleHex(wallPartPair.first));
- }
- }
- }
- return attackableBattleHexes;
- }
- ESpellCastProblem::ESpellCastProblem CBattleInfoCallback::battleIsImmune(const CGHeroInstance * caster, const CSpell * spell, ECastingMode::ECastingMode mode, BattleHex dest) const
- {
- RETURN_IF_NOT_BATTLE(ESpellCastProblem::INVALID);
- // Get stack at destination hex -> subject of our spell.
- const CStack * subject = battleGetStackByPos(dest, !spell->isRisingSpell()); //only alive if not rising spell
- if(subject)
- {
- if (spell->isPositive() && subject->hasBonusOfType(Bonus::RECEPTIVE)) //accept all positive spells
- return ESpellCastProblem::OK;
- if (spell->isImmuneBy(subject)) //TODO: move all logic to spellhandler
- return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
- switch (spell->id) //TODO: more general logic for new spells?
- {
- case SpellID::CLONE:
- {
- //can't clone already cloned creature
- if (vstd::contains(subject->state, EBattleStackState::CLONED))
- return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
- //TODO: how about stacks casting Clone?
- //currently Clone casted by stack is assumed Expert level
- ui8 schoolLevel;
- if (caster)
- {
- schoolLevel = caster->getSpellSchoolLevel(spell);
- }
- else
- {
- schoolLevel = 3;
- }
- if (schoolLevel < 3)
- {
- int maxLevel = (std::max(schoolLevel, (ui8)1) + 4);
- int creLevel = subject->getCreature()->level;
- if (maxLevel < creLevel) //tier 1-5 for basic, 1-6 for advanced, any level for expert
- return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
- }
- }
- break;
- case SpellID::DISPEL_HELPFUL_SPELLS:
- {
- TBonusListPtr spellBon = subject->getSpellBonuses();
- bool hasPositiveSpell = false;
- for(const Bonus * b : *spellBon)
- {
- if(SpellID(b->sid).toSpell()->isPositive())
- {
- hasPositiveSpell = true;
- break;
- }
- }
- if(!hasPositiveSpell)
- {
- return ESpellCastProblem::NO_SPELLS_TO_DISPEL;
- }
- }
- break;
- }
- if (spell->isRisingSpell())
- {
- if(subject->count >= subject->baseAmount)
- return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
-
- if (caster) //FIXME: Archangels can cast immune stack
- {
- auto maxHealth = calculateHealedHP (caster, spell, subject);
- if (maxHealth < subject->MaxHealth()) //must be able to rise at least one full creature
- return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
- }
- }
- else if(spell->id == SpellID::HYPNOTIZE && caster) //do not resist hypnotize casted after attack, for example
- {
- //TODO: what with other creatures casting hypnotize, Faerie Dragons style?
- ui64 subjectHealth = (subject->count - 1) * subject->MaxHealth() + subject->firstHPleft;
- //apply 'damage' bonus for hypnotize, including hero specialty
- ui64 maxHealth = calculateSpellBonus (caster->getPrimSkillLevel(PrimarySkill::SPELL_POWER)
- * spell->power + spell->getPower(caster->getSpellSchoolLevel(spell)), spell, caster, subject);
- if (subjectHealth > maxHealth)
- return ESpellCastProblem::STACK_IMMUNE_TO_SPELL;
- }
- }
- else //no target stack on this tile
- {
- if(spell->getTargetType() == CSpell::CREATURE)
- {
- if(caster && mode == ECastingMode::HERO_CASTING) //TODO why???
- {
- const CSpell::TargetInfo ti = spell->getTargetInfo(caster->getSpellSchoolLevel(spell));
-
- if(!ti.massive)
- return ESpellCastProblem::WRONG_SPELL_TARGET;
- }
- else
- {
- return ESpellCastProblem::WRONG_SPELL_TARGET;
- }
-
- }
- }
- return ESpellCastProblem::OK;
- }
- ESpellCastProblem::ESpellCastProblem CBattleInfoCallback::battleCanCastThisSpell( PlayerColor player, const CSpell * spell, ECastingMode::ECastingMode mode ) const
- {
- RETURN_IF_NOT_BATTLE(ESpellCastProblem::INVALID);
- const ui8 side = playerToSide(player);
- if(!battleDoWeKnowAbout(side))
- return ESpellCastProblem::INVALID;
- ESpellCastProblem::ESpellCastProblem genProblem = battleCanCastSpell(player, mode);
- if(genProblem != ESpellCastProblem::OK)
- return genProblem;
- //Casting hero, set only if he is an actual caster.
- const CGHeroInstance *castingHero = mode == ECastingMode::HERO_CASTING
- ? battleGetFightingHero(side)
- : nullptr;
- switch(mode)
- {
- case ECastingMode::HERO_CASTING:
- {
- assert(castingHero);
- if(!castingHero->canCastThisSpell(spell))
- return ESpellCastProblem::HERO_DOESNT_KNOW_SPELL;
- if(castingHero->mana < battleGetSpellCost(spell, castingHero)) //not enough mana
- return ESpellCastProblem::NOT_ENOUGH_MANA;
- }
- break;
- }
- if(!spell->combatSpell)
- return ESpellCastProblem::ADVMAP_SPELL_INSTEAD_OF_BATTLE_SPELL;
- if(spell->isNegative() || spell->hasEffects())
- {
- bool allStacksImmune = true;
- //we are interested only in enemy stacks when casting offensive spells
- //TODO: should hero be able to cast non-smart negative spell if all enemy stacks are immune?
- auto stacks = spell->isNegative() ? battleAliveStacks(!side) : battleAliveStacks();
- for(auto stack : stacks)
- {
- if(!battleIsImmune(castingHero, spell, mode, stack->position))
- {
- allStacksImmune = false;
- break;
- }
- }
- if(allStacksImmune)
- return ESpellCastProblem::NO_APPROPRIATE_TARGET;
- }
- if(battleMaxSpellLevel() < spell->level) //effect like Recanter's Cloak or Orb of Inhibition
- return ESpellCastProblem::SPELL_LEVEL_LIMIT_EXCEEDED;
- //IDs of summon elemental spells (fire, earth, water, air)
- int spellIDs[] = { SpellID::SUMMON_FIRE_ELEMENTAL, SpellID::SUMMON_EARTH_ELEMENTAL,
- SpellID::SUMMON_WATER_ELEMENTAL, SpellID::SUMMON_AIR_ELEMENTAL };
- //(fire, earth, water, air) elementals
- int creIDs[] = {CreatureID::FIRE_ELEMENTAL, CreatureID::EARTH_ELEMENTAL,
- CreatureID::WATER_ELEMENTAL, CreatureID::AIR_ELEMENTAL};
- int arpos = vstd::find_pos(spellIDs, spell->id);
- if(arpos < ARRAY_COUNT(spellIDs))
- {
- //check if there are summoned elementals of other type
- for( const CStack * st : battleAliveStacks())
- if(vstd::contains(st->state, EBattleStackState::SUMMONED) && st->getCreature()->idNumber != creIDs[arpos])
- return ESpellCastProblem::ANOTHER_ELEMENTAL_SUMMONED;
- }
- //checking if there exists an appropriate target
- switch(spell->getTargetType())
- {
- case CSpell::CREATURE:
- if(mode == ECastingMode::HERO_CASTING)
- {
- const CGHeroInstance * caster = battleGetFightingHero(side);
- const CSpell::TargetInfo ti = spell->getTargetInfo(caster->getSpellSchoolLevel(spell));
- bool targetExists = false;
- for(const CStack * stack : battleGetAllStacks()) //dead stacks will be immune anyway
- {
- bool immune = battleIsImmune(caster, spell, mode, stack->position) != ESpellCastProblem::OK;
- bool casterStack = stack->owner == caster->getOwner();
-
- if(!immune)
- switch (spell->positiveness)
- {
- case CSpell::POSITIVE:
- if(casterStack || !ti.smart)
- {
- targetExists = true;
- break;
- }
- break;
- case CSpell::NEUTRAL:
- targetExists = true;
- break;
- break;
- case CSpell::NEGATIVE:
- if(!casterStack || !ti.smart)
- {
- targetExists = true;
- break;
- }
- break;
- }
- }
- if(!targetExists)
- {
- return ESpellCastProblem::NO_APPROPRIATE_TARGET;
- }
- }
- break;
- case CSpell::OBSTACLE:
- break;
- }
- return ESpellCastProblem::OK;
- }
- std::vector<BattleHex> CBattleInfoCallback::battleGetPossibleTargets(PlayerColor player, const CSpell *spell) const
- {
- std::vector<BattleHex> ret;
- RETURN_IF_NOT_BATTLE(ret);
- auto mode = ECastingMode::HERO_CASTING; //TODO get rid of this!
- switch(spell->getTargetType())
- {
- case CSpell::CREATURE:
- {
- const CGHeroInstance * caster = battleGetFightingHero(playerToSide(player)); //TODO
- const CSpell::TargetInfo ti = spell->getTargetInfo(caster->getSpellSchoolLevel(spell));
-
- for(const CStack * stack : battleAliveStacks())
- {
- bool immune = battleIsImmune(caster, spell, mode, stack->position) != ESpellCastProblem::OK;
- bool casterStack = stack->owner == caster->getOwner();
-
- if(!immune)
- switch (spell->positiveness)
- {
- case CSpell::POSITIVE:
- if(casterStack || ti.smart)
- ret.push_back(stack->position);
- break;
- case CSpell::NEUTRAL:
- ret.push_back(stack->position);
- break;
- case CSpell::NEGATIVE:
- if(!casterStack || ti.smart)
- ret.push_back(stack->position);
- break;
- }
- }
- }
- break;
- default:
- logGlobal->errorStream() << "FIXME " << __FUNCTION__ << " doesn't work with target type " << spell->getTargetType();
- }
- return ret;
- }
- ui32 CBattleInfoCallback::battleGetSpellCost(const CSpell * sp, const CGHeroInstance * caster) const
- {
- RETURN_IF_NOT_BATTLE(-1);
- //TODO should be replaced using bonus system facilities (propagation onto battle node)
- ui32 ret = caster->getSpellCost(sp);
- //checking for friendly stacks reducing cost of the spell and
- //enemy stacks increasing it
- si32 manaReduction = 0;
- si32 manaIncrease = 0;
- for(auto stack : battleAliveStacks())
- {
- if(stack->owner == caster->tempOwner && stack->hasBonusOfType(Bonus::CHANGES_SPELL_COST_FOR_ALLY) )
- {
- vstd::amax(manaReduction, stack->valOfBonuses(Bonus::CHANGES_SPELL_COST_FOR_ALLY));
- }
- if( stack->owner != caster->tempOwner && stack->hasBonusOfType(Bonus::CHANGES_SPELL_COST_FOR_ENEMY) )
- {
- vstd::amax(manaIncrease, stack->valOfBonuses(Bonus::CHANGES_SPELL_COST_FOR_ENEMY));
- }
- }
- return ret - manaReduction + manaIncrease;
- }
- ESpellCastProblem::ESpellCastProblem CBattleInfoCallback::battleCanCastThisSpellHere( PlayerColor player, const CSpell * spell, ECastingMode::ECastingMode mode, BattleHex dest ) const
- {
- RETURN_IF_NOT_BATTLE(ESpellCastProblem::INVALID);
- ESpellCastProblem::ESpellCastProblem moreGeneralProblem = battleCanCastThisSpell(player, spell, mode);
- if(moreGeneralProblem != ESpellCastProblem::OK)
- return moreGeneralProblem;
- if(spell->getTargetType() == CSpell::OBSTACLE)
- {
- if(spell->id == SpellID::REMOVE_OBSTACLE)
- {
- if(auto obstacle = battleGetObstacleOnPos(dest, false))
- {
- switch (obstacle->obstacleType)
- {
- case CObstacleInstance::ABSOLUTE_OBSTACLE: //cliff-like obstacles can't be removed
- case CObstacleInstance::MOAT:
- return ESpellCastProblem::NO_APPROPRIATE_TARGET;
- case CObstacleInstance::USUAL:
- return ESpellCastProblem::OK;
- // //TODO FIRE_WALL only for ADVANCED level casters
- // case CObstacleInstance::FIRE_WALL:
- // return
- // //TODO other magic obstacles for EXPERT
- // case CObstacleInstance::QUICKSAND:
- // case CObstacleInstance::LAND_MINE:
- // case CObstacleInstance::FORCE_FIELD:
- // return
- default:
- // assert(0);
- return ESpellCastProblem::OK;
- }
- }
- }
- //isObstacleOnTile(dest)
- //
- //
- //TODO
- //assert that it's remove obstacle
- //rules whether we can remove spell-created obstacle
- return ESpellCastProblem::NO_APPROPRIATE_TARGET;
- }
- //get dead stack if we cast resurrection or animate dead
- const CStack *deadStack = getStackIf([dest](const CStack *s) { return !s->alive() && s->coversPos(dest); });
- const CStack *aliveStack = getStackIf([dest](const CStack *s) { return s->alive() && s->coversPos(dest);});
- if(spell->isRisingSpell())
- {
- if(!deadStack && !aliveStack)
- return ESpellCastProblem::NO_APPROPRIATE_TARGET;
- if(spell->id == SpellID::ANIMATE_DEAD && deadStack && !deadStack->hasBonusOfType(Bonus::UNDEAD))
- return ESpellCastProblem::NO_APPROPRIATE_TARGET;
- if(deadStack && deadStack->owner != player) //you can resurrect only your own stacks //FIXME: it includes alive stacks as well
- return ESpellCastProblem::NO_APPROPRIATE_TARGET;
- }
- else if(spell->getTargetType() == CSpell::CREATURE)
- {
- if(!aliveStack)
- return ESpellCastProblem::NO_APPROPRIATE_TARGET;
- if(spell->isNegative() && aliveStack->owner == player)
- return ESpellCastProblem::NO_APPROPRIATE_TARGET;
- if(spell->isPositive() && aliveStack->owner != player)
- return ESpellCastProblem::NO_APPROPRIATE_TARGET;
- }
- if (mode == ECastingMode::HERO_CASTING)
- return battleIsImmune(battleGetFightingHero(playerToSide(player)), spell, mode, dest);
- else
- return battleIsImmune(nullptr, spell, mode, dest);
- }
- ui32 CBattleInfoCallback::calculateSpellBonus(ui32 baseDamage, const CSpell * sp, const CGHeroInstance * caster, const CStack * affectedCreature) const
- {
- ui32 ret = baseDamage;
- //applying sorcery secondary skill
- if(caster)
- {
- ret *= (100.0 + caster->valOfBonuses(Bonus::SECONDARY_SKILL_PREMY, SecondarySkill::SORCERY)) / 100.0;
- ret *= (100.0 + caster->valOfBonuses(Bonus::SPELL_DAMAGE) + caster->valOfBonuses(Bonus::SPECIFIC_SPELL_DAMAGE, sp->id.toEnum())) / 100.0;
- if(sp->air)
- ret *= (100.0 + caster->valOfBonuses(Bonus::AIR_SPELL_DMG_PREMY)) / 100.0;
- else if(sp->fire) //only one type of bonus for Magic Arrow
- ret *= (100.0 + caster->valOfBonuses(Bonus::FIRE_SPELL_DMG_PREMY)) / 100.0;
- else if(sp->water)
- ret *= (100.0 + caster->valOfBonuses(Bonus::WATER_SPELL_DMG_PREMY)) / 100.0;
- else if(sp->earth)
- ret *= (100.0 + caster->valOfBonuses(Bonus::EARTH_SPELL_DMG_PREMY)) / 100.0;
- if (affectedCreature && affectedCreature->getCreature()->level) //Hero specials like Solmyr, Deemer
- ret *= (100. + ((caster->valOfBonuses(Bonus::SPECIAL_SPELL_LEV, sp->id.toEnum()) * caster->level) / affectedCreature->getCreature()->level)) / 100.0;
- }
- return ret;
- }
- ui32 CBattleInfoCallback::calculateSpellDmg( const CSpell * sp, const CGHeroInstance * caster, const CStack * affectedCreature, int spellSchoolLevel, int usedSpellPower ) const
- {
- ui32 ret = 0; //value to return
- //check if spell really does damage - if not, return 0
- if(!sp->isDamageSpell())
- return 0;
- ret = usedSpellPower * sp->power;
- ret += sp->getPower(spellSchoolLevel);
- //affected creature-specific part
- if(affectedCreature)
- {
- //applying protections - when spell has more then one elements, only one protection should be applied (I think)
- if(sp->air && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, 0)) //air spell & protection from air
- {
- ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, 0);
- ret /= 100;
- }
- else if(sp->fire && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, 1)) //fire spell & protection from fire
- {
- ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, 1);
- ret /= 100;
- }
- else if(sp->water && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, 2)) //water spell & protection from water
- {
- ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, 2);
- ret /= 100;
- }
- else if (sp->earth && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, 3)) //earth spell & protection from earth
- {
- ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, 3);
- ret /= 100;
- }
- //general spell dmg reduction
- //FIXME?
- if(sp->air && affectedCreature->hasBonusOfType(Bonus::SPELL_DAMAGE_REDUCTION, -1))
- {
- ret *= affectedCreature->valOfBonuses(Bonus::SPELL_DAMAGE_REDUCTION, -1);
- ret /= 100;
- }
- //dmg increasing
- if( affectedCreature->hasBonusOfType(Bonus::MORE_DAMAGE_FROM_SPELL, sp->id) )
- {
- ret *= 100 + affectedCreature->valOfBonuses(Bonus::MORE_DAMAGE_FROM_SPELL, sp->id.toEnum());
- ret /= 100;
- }
- }
- ret = calculateSpellBonus(ret, sp, caster, affectedCreature);
- return ret;
- }
- std::set<const CStack*> CBattleInfoCallback::getAffectedCreatures(const CSpell * spell, int skillLevel, PlayerColor attackerOwner, BattleHex destinationTile)
- {
- std::set<const CStack*> attackedCres; /*std::set to exclude multiple occurrences of two hex creatures*/
- const ui8 attackerSide = playerToSide(attackerOwner) == 1;
- const auto attackedHexes = spell->rangeInHexes(destinationTile, skillLevel, attackerSide);
- const bool onlyAlive = !spell->isRisingSpell(); //when casting resurrection or animate dead we should be allow to select dead stack
- const CSpell::TargetInfo ti = spell->getTargetInfo(skillLevel);
- //TODO: more generic solution for mass spells
- if(spell->id == SpellID::DEATH_RIPPLE || spell->id == SpellID::DESTROY_UNDEAD )
- {
- for(const CStack *stack : battleGetAllStacks())
- {
- if((spell->id == SpellID::DEATH_RIPPLE && !stack->getCreature()->isUndead()) //death ripple
- || (spell->id == SpellID::DESTROY_UNDEAD && stack->getCreature()->isUndead()) //destroy undead
- )
- {
- if(stack->isValidTarget())
- attackedCres.insert(stack);
- }
- }
- }
- else if (spell->id == SpellID::CHAIN_LIGHTNING)
- {
- std::set<BattleHex> possibleHexes;
- for (auto stack : battleGetAllStacks())
- {
- if (stack->isValidTarget())
- {
- for (auto hex : stack->getHexes())
- {
- possibleHexes.insert (hex);
- }
- }
- }
- int targetsOnLevel[4] = {4, 4, 5, 5};
- BattleHex lightningHex = destinationTile;
- for (int i = 0; i < targetsOnLevel[skillLevel]; ++i)
- {
- auto stack = battleGetStackByPos (lightningHex, true);
- if (!stack)
- break;
- attackedCres.insert (stack);
- for (auto hex : stack->getHexes())
- {
- possibleHexes.erase (hex); //can't hit same place twice
- }
- if (possibleHexes.empty()) //not enough targets
- break;
- lightningHex = BattleHex::getClosestTile (stack->attackerOwned, destinationTile, possibleHexes);
- }
- }
- else if (spell->getLevelInfo(skillLevel).range.size() > 1) //custom many-hex range
- {
- for(BattleHex hex : attackedHexes)
- {
- if(const CStack * st = battleGetStackByPos(hex, onlyAlive))
- {
- if (spell->id == SpellID::DEATH_CLOUD) //Death Cloud //TODO: fireball and fire immunity
- {
- if (st->isLiving() || st->coversPos(destinationTile)) //directly hit or alive
- {
- attackedCres.insert(st);
- }
- }
- else
- attackedCres.insert(st);
- }
- }
- }
- else if(spell->getTargetType() == CSpell::CREATURE)
- {
- if (ti.massive)
- {
- TStacks stacks = battleGetAllStacks();
- vstd::erase_if(stacks,[&](const CStack * stack){
- return ti.smart && spell->isNegative() && stack->owner == attackerOwner;
- });
- vstd::erase_if(stacks,[&](const CStack * stack){
- return ti.smart && spell->isPositive() && stack->owner != attackerOwner;
- });
- vstd::erase_if(stacks,[&](const CStack * stack){
- return !stack->isValidTarget(!onlyAlive);
- });
-
- for (auto stack : stacks)
- attackedCres.insert(stack);
- }
- else
- {
- if(const CStack * st = battleGetStackByPos(destinationTile, onlyAlive))
- attackedCres.insert(st);
- }
-
- }
- else //custom range from attackedHexes
- {
- for(BattleHex hex : attackedHexes)
- {
- if(const CStack * st = battleGetStackByPos(hex, onlyAlive))
- attackedCres.insert(st);
- }
- }
- return attackedCres;
- }
- const CStack * CBattleInfoCallback::getStackIf(std::function<bool(const CStack*)> pred) const
- {
- RETURN_IF_NOT_BATTLE(nullptr);
- auto stacks = battleGetAllStacks();
- auto stackItr = range::find_if(stacks, pred);
- return stackItr == stacks.end()
- ? nullptr
- : *stackItr;
- }
- bool CBattleInfoCallback::battleIsStackBlocked(const CStack * stack) const
- {
- RETURN_IF_NOT_BATTLE(false);
- if(stack->hasBonusOfType(Bonus::SIEGE_WEAPON)) //siege weapons cannot be blocked
- return false;
- for(const CStack * s : batteAdjacentCreatures(stack))
- {
- if (s->owner != stack->owner) //blocked by enemy stack
- return true;
- }
- return false;
- }
- std::set<const CStack*> CBattleInfoCallback:: batteAdjacentCreatures(const CStack * stack) const
- {
- std::set<const CStack*> stacks;
- RETURN_IF_NOT_BATTLE(stacks);
- for (BattleHex hex : stack->getSurroundingHexes())
- if(const CStack *neighbour = battleGetStackByPos(hex, true))
- stacks.insert(neighbour);
- return stacks;
- }
- SpellID CBattleInfoCallback::getRandomBeneficialSpell(const CStack * subject) const
- {
- RETURN_IF_NOT_BATTLE(SpellID::NONE);
- std::vector<SpellID> possibleSpells;
- for(const CSpell *spell : VLC->spellh->objects)
- {
- if (spell->isPositive()) //only positive
- {
- if (subject->hasBonusFrom(Bonus::SPELL_EFFECT, spell->id)
- || battleCanCastThisSpellHere(subject->owner, spell, ECastingMode::CREATURE_ACTIVE_CASTING, subject->position) != ESpellCastProblem::OK)
- continue;
- switch (spell->id)
- {
- case SpellID::SHIELD:
- case SpellID::FIRE_SHIELD: // not if all enemy units are shooters
- {
- auto walker = getStackIf([&](const CStack *stack) //look for enemy, non-shooting stack
- {
- return stack->owner != subject->owner && !stack->shots;
- });
- if (!walker)
- continue;
- }
- break;
- case SpellID::AIR_SHIELD: //only against active shooters
- {
- auto shooter = getStackIf([&](const CStack *stack) //look for enemy, non-shooting stack
- {
- return stack->owner != subject->owner && stack->hasBonusOfType(Bonus::SHOOTER) && stack->shots;
- });
- if (!shooter)
- continue;
- }
- break;
- case SpellID::ANTI_MAGIC:
- case SpellID::MAGIC_MIRROR:
- {
- if (!battleHasHero(subject->attackerOwned)) //only if there is enemy hero
- continue;
- }
- break;
- case SpellID::CURE: //only damaged units - what about affected by curse?
- {
- if (subject->firstHPleft >= subject->MaxHealth())
- continue;
- }
- break;
- case SpellID::BLOODLUST:
- {
- if (subject->shots) //if can shoot - only if enemy uits are adjacent
- continue;
- }
- break;
- case SpellID::PRECISION:
- {
- if (!(subject->hasBonusOfType(Bonus::SHOOTER) && subject->shots))
- continue;
- }
- break;
- case SpellID::SLAYER://only if monsters are present
- {
- auto kingMonster = getStackIf([&](const CStack *stack) -> bool //look for enemy, non-shooting stack
- {
- const auto isKing = Selector::type(Bonus::KING1)
- .Or(Selector::type(Bonus::KING2))
- .Or(Selector::type(Bonus::KING3));
- return stack->owner != subject->owner && stack->hasBonus(isKing);
- });
- if (!kingMonster)
- continue;
- }
- break;
- case SpellID::CLONE: //not allowed
- continue;
- break;
- }
- possibleSpells.push_back(spell->id);
- }
- }
- if (possibleSpells.size())
- return possibleSpells[rand() % possibleSpells.size()];
- else
- return SpellID::NONE;
- }
- SpellID CBattleInfoCallback::getRandomCastedSpell(const CStack * caster) const
- {
- RETURN_IF_NOT_BATTLE(SpellID::NONE);
- TBonusListPtr bl = caster->getBonuses(Selector::type(Bonus::SPELLCASTER));
- if (!bl->size())
- return SpellID::NONE;
- int totalWeight = 0;
- for(Bonus * b : *bl)
- {
- totalWeight += std::max(b->additionalInfo, 1); //minimal chance to cast is 1
- }
- int randomPos = rand() % totalWeight;
- for(Bonus * b : *bl)
- {
- randomPos -= std::max(b->additionalInfo, 1);
- if(randomPos < 0)
- {
- return SpellID(b->subtype);
- }
- }
- return SpellID::NONE;
- }
- int CBattleInfoCallback::battleGetSurrenderCost(PlayerColor Player) const
- {
- RETURN_IF_NOT_BATTLE(-3);
- if(!battleCanSurrender(Player))
- return -1;
- int ret = 0;
- double discount = 0;
- for(const CStack *s : battleAliveStacks(playerToSide(Player)))
- if(s->base) //we pay for our stack that comes from our army slots - condition eliminates summoned cres and war machines
- ret += s->getCreature()->cost[Res::GOLD] * s->count;
- if(const CGHeroInstance *h = battleGetFightingHero(playerToSide(Player)))
- discount += h->valOfBonuses(Bonus::SURRENDER_DISCOUNT);
- ret *= (100.0 - discount) / 100.0;
- vstd::amax(ret, 0); //no negative costs for >100% discounts (impossible in original H3 mechanics, but some day...)
- return ret;
- }
- si8 CBattleInfoCallback::battleMaxSpellLevel() const
- {
- const CBonusSystemNode *node = nullptr;
- if(const CGHeroInstance *h = battleGetFightingHero(battleGetMySide()))
- node = h;
- //TODO else use battle node
- if(!node)
- return GameConstants::SPELL_LEVELS;
- //We can't "just get value" - it'd be 0 if there are bonuses (and all would be blocked)
- auto b = node->getBonuses(Selector::type(Bonus::BLOCK_MAGIC_ABOVE));
- if(b->size())
- return b->totalValue();
- return GameConstants::SPELL_LEVELS;
- }
- boost::optional<int> CBattleInfoCallback::battleIsFinished() const
- {
- auto stacks = battleGetAllStacks();
- //checking winning condition
- bool hasStack[2]; //hasStack[0] - true if attacker has a living stack; defender similarly
- hasStack[0] = hasStack[1] = false;
- for(auto & stack : stacks)
- {
- if(stack->alive() && !stack->hasBonusOfType(Bonus::SIEGE_WEAPON))
- {
- hasStack[1-stack->attackerOwned] = true;
- }
- }
- if(!hasStack[0] && !hasStack[1])
- return 2;
- if(!hasStack[1])
- return 0;
- if(!hasStack[0])
- return 1;
- return boost::none;
- }
- bool AccessibilityInfo::accessible(BattleHex tile, const CStack *stack) const
- {
- return accessible(tile, stack->doubleWide(), stack->attackerOwned);
- }
- bool AccessibilityInfo::accessible(BattleHex tile, bool doubleWide, bool attackerOwned) const
- {
- // All hexes that stack would cover if standing on tile have to be accessible.
- for(auto hex : CStack::getHexes(tile, doubleWide, attackerOwned))
- {
- // If the hex is out of range then the tile isn't accessible
- if(!hex.isValid())
- return false;
- // If we're no defender which step on gate and the hex isn't accessible, then the tile
- // isn't accessible
- else if(at(hex) != EAccessibility::ACCESSIBLE &&
- !(at(hex) == EAccessibility::GATE && !attackerOwned))
- return false;
- }
- return true;
- }
- bool AccessibilityInfo::occupiable(const CStack *stack, BattleHex tile) const
- {
- //obviously, we can occupy tile by standing on it
- if(accessible(tile, stack))
- return true;
- if(stack->doubleWide())
- {
- //Check the tile next to -> if stack stands there, it'll also occupy considered hex
- const BattleHex anotherTile = tile + (stack->attackerOwned ? BattleHex::RIGHT : BattleHex::LEFT);
- if(accessible(anotherTile, stack))
- return true;
- }
- return false;
- }
- ReachabilityInfo::Parameters::Parameters()
- {
- stack = nullptr;
- perspective = BattlePerspective::ALL_KNOWING;
- attackerOwned = doubleWide = flying = false;
- }
- ReachabilityInfo::Parameters::Parameters(const CStack *Stack)
- {
- stack = Stack;
- perspective = (BattlePerspective::BattlePerspective)(!Stack->attackerOwned);
- startPosition = Stack->position;
- doubleWide = stack->doubleWide();
- attackerOwned = stack->attackerOwned;
- flying = stack->hasBonusOfType(Bonus::FLYING);
- knownAccessible = stack->getHexes();
- }
- ESpellCastProblem::ESpellCastProblem CPlayerBattleCallback::battleCanCastThisSpell(const CSpell * spell) const
- {
- RETURN_IF_NOT_BATTLE(ESpellCastProblem::INVALID);
- ASSERT_IF_CALLED_WITH_PLAYER
- return CBattleInfoCallback::battleCanCastThisSpell(*player, spell, ECastingMode::HERO_CASTING);
- }
- ESpellCastProblem::ESpellCastProblem CPlayerBattleCallback::battleCanCastThisSpell(const CSpell * spell, BattleHex destination) const
- {
- RETURN_IF_NOT_BATTLE(ESpellCastProblem::INVALID);
- ASSERT_IF_CALLED_WITH_PLAYER
- return battleCanCastThisSpellHere(*player, spell, ECastingMode::HERO_CASTING, destination);
- }
- ESpellCastProblem::ESpellCastProblem CPlayerBattleCallback::battleCanCreatureCastThisSpell(const CSpell * spell, BattleHex destination) const
- {
- RETURN_IF_NOT_BATTLE(ESpellCastProblem::INVALID);
- ASSERT_IF_CALLED_WITH_PLAYER
- return battleCanCastThisSpellHere(*player, spell, ECastingMode::CREATURE_ACTIVE_CASTING, destination);
- }
- bool CPlayerBattleCallback::battleCanFlee() const
- {
- RETURN_IF_NOT_BATTLE(false);
- ASSERT_IF_CALLED_WITH_PLAYER
- return CBattleInfoEssentials::battleCanFlee(*player);
- }
- TStacks CPlayerBattleCallback::battleGetStacks(EStackOwnership whose /*= MINE_AND_ENEMY*/, bool onlyAlive /*= true*/) const
- {
- TStacks ret;
- RETURN_IF_NOT_BATTLE(ret);
- if(whose != MINE_AND_ENEMY)
- {
- ASSERT_IF_CALLED_WITH_PLAYER
- }
- vstd::copy_if(battleGetAllStacks(), std::back_inserter(ret), [=](const CStack *s) -> bool
- {
- const bool ownerMatches = (whose == MINE_AND_ENEMY)
- || (whose == ONLY_MINE && s->owner == player)
- || (whose == ONLY_ENEMY && s->owner != player);
- const bool alivenessMatches = s->alive() || !onlyAlive;
- return ownerMatches && alivenessMatches;
- });
- return ret;
- }
- int CPlayerBattleCallback::battleGetSurrenderCost() const
- {
- RETURN_IF_NOT_BATTLE(-3)
- ASSERT_IF_CALLED_WITH_PLAYER
- return CBattleInfoCallback::battleGetSurrenderCost(*player);
- }
- bool CPlayerBattleCallback::battleCanCastSpell(ESpellCastProblem::ESpellCastProblem *outProblem /*= nullptr*/) const
- {
- RETURN_IF_NOT_BATTLE(false);
- ASSERT_IF_CALLED_WITH_PLAYER
- auto problem = CBattleInfoCallback::battleCanCastSpell(*player, ECastingMode::HERO_CASTING);
- if(outProblem)
- *outProblem = problem;
- return problem == ESpellCastProblem::OK;
- }
- const CGHeroInstance * CPlayerBattleCallback::battleGetMyHero() const
- {
- return CBattleInfoEssentials::battleGetFightingHero(battleGetMySide());
- }
- InfoAboutHero CPlayerBattleCallback::battleGetEnemyHero() const
- {
- return battleGetHeroInfo(!battleGetMySide());
- }
- BattleAttackInfo::BattleAttackInfo(const CStack *Attacker, const CStack *Defender, bool Shooting)
- {
- attacker = Attacker;
- defender = Defender;
- attackerBonuses = Attacker;
- defenderBonuses = Defender;
- attackerPosition = Attacker->position;
- defenderPosition = Defender->position;
- attackerCount = Attacker->count;
- defenderCount = Defender->count;
- shooting = Shooting;
- chargedFields = 0;
- luckyHit = false;
- deathBlow = false;
- ballistaDoubleDamage = false;
- }
- BattleAttackInfo BattleAttackInfo::reverse() const
- {
- BattleAttackInfo ret = *this;
- std::swap(ret.attacker, ret.defender);
- std::swap(ret.attackerBonuses, ret.defenderBonuses);
- std::swap(ret.attackerPosition, ret.defenderPosition);
- std::swap(ret.attackerCount, ret.defenderCount);
- ret.shooting = false;
- ret.chargedFields = 0;
- ret.luckyHit = ret.ballistaDoubleDamage = ret.deathBlow = false;
- return ret;
- }
|