CGameState.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  1. #pragma once
  2. //#ifndef _MSC_VER
  3. #include "CCreatureHandler.h"
  4. #include "VCMI_Lib.h"
  5. #include "mapping/CMap.h"
  6. //#endif
  7. #include "HeroBonus.h"
  8. #include "CCreatureSet.h"
  9. #include "ConstTransitivePtr.h"
  10. #include "IGameCallback.h"
  11. #include "ResourceSet.h"
  12. #include "int3.h"
  13. #include "CObjectHandler.h"
  14. #include "IGameCallback.h"
  15. /*
  16. * CGameState.h, part of VCMI engine
  17. *
  18. * Authors: listed in file AUTHORS in main folder
  19. *
  20. * License: GNU General Public License v2.0 or later
  21. * Full text of license available in license.txt file, in main folder
  22. *
  23. */
  24. class CTown;
  25. class CCallback;
  26. class IGameCallback;
  27. class CCreatureSet;
  28. class CStack;
  29. class CQuest;
  30. class CGHeroInstance;
  31. class CGTownInstance;
  32. class CArmedInstance;
  33. class CGDwelling;
  34. class CObjectScript;
  35. class CGObjectInstance;
  36. class CCreature;
  37. class CMap;
  38. struct StartInfo;
  39. struct SDL_Surface;
  40. class CMapHandler;
  41. class CPathfinder;
  42. struct SetObjectProperty;
  43. struct MetaString;
  44. struct CPack;
  45. class CSpell;
  46. struct TerrainTile;
  47. class CHeroClass;
  48. class CCampaign;
  49. class CCampaignState;
  50. class IModableArt;
  51. class CGGarrison;
  52. class CGameInfo;
  53. struct QuestInfo;
  54. class CQuest;
  55. class CCampaignScenario;
  56. namespace boost
  57. {
  58. class shared_mutex;
  59. }
  60. //numbers of creatures are exact numbers if detailed else they are quantity ids (0 - a few, 1 - several and so on; additionally -1 - unknown)
  61. struct ArmyDescriptor : public std::map<SlotID, CStackBasicDescriptor>
  62. {
  63. bool isDetailed;
  64. DLL_LINKAGE ArmyDescriptor(const CArmedInstance *army, bool detailed); //not detailed -> quantity ids as count
  65. DLL_LINKAGE ArmyDescriptor();
  66. DLL_LINKAGE int getStrength() const;
  67. };
  68. struct DLL_LINKAGE InfoAboutArmy
  69. {
  70. PlayerColor owner;
  71. std::string name;
  72. ArmyDescriptor army;
  73. InfoAboutArmy();
  74. InfoAboutArmy(const CArmedInstance *Army, bool detailed);
  75. void initFromArmy(const CArmedInstance *Army, bool detailed);
  76. };
  77. struct DLL_LINKAGE InfoAboutHero : public InfoAboutArmy
  78. {
  79. private:
  80. void assign(const InfoAboutHero & iah);
  81. public:
  82. struct DLL_LINKAGE Details
  83. {
  84. std::vector<si32> primskills;
  85. si32 mana, luck, morale;
  86. } *details;
  87. const CHeroClass *hclass;
  88. int portrait;
  89. InfoAboutHero();
  90. InfoAboutHero(const InfoAboutHero & iah);
  91. InfoAboutHero(const CGHeroInstance *h, bool detailed);
  92. ~InfoAboutHero();
  93. InfoAboutHero & operator=(const InfoAboutHero & iah);
  94. void initFromHero(const CGHeroInstance *h, bool detailed);
  95. };
  96. /// Struct which holds a int information about a town
  97. struct DLL_LINKAGE InfoAboutTown : public InfoAboutArmy
  98. {
  99. struct DLL_LINKAGE Details
  100. {
  101. si32 hallLevel, goldIncome;
  102. bool customRes;
  103. bool garrisonedHero;
  104. } *details;
  105. const CTown *tType;
  106. si32 built;
  107. si32 fortLevel; //0 - none
  108. InfoAboutTown();
  109. InfoAboutTown(const CGTownInstance *t, bool detailed);
  110. ~InfoAboutTown();
  111. void initFromTown(const CGTownInstance *t, bool detailed);
  112. };
  113. // typedef si32 TResourceUnit;
  114. // typedef std::vector<si32> TResourceVector;
  115. // typedef std::set<si32> TResourceSet;
  116. struct DLL_LINKAGE SThievesGuildInfo
  117. {
  118. std::vector<PlayerColor> playerColors; //colors of players that are in-game
  119. std::vector< std::vector< PlayerColor > > numOfTowns, numOfHeroes, gold, woodOre, mercSulfCrystGems, obelisks, artifacts, army, income; // [place] -> [colours of players]
  120. std::map<PlayerColor, InfoAboutHero> colorToBestHero; //maps player's color to his best heros'
  121. std::map<PlayerColor, EAiTactic::EAiTactic> personality; // color to personality // ai tactic
  122. std::map<PlayerColor, si32> bestCreature; // color to ID // id or -1 if not known
  123. // template <typename Handler> void serialize(Handler &h, const int version)
  124. // {
  125. // h & playerColors & numOfTowns & numOfHeroes & gold & woodOre & mercSulfCrystGems & obelisks & artifacts & army & income;
  126. // h & colorToBestHero & personality & bestCreature;
  127. // }
  128. };
  129. struct DLL_LINKAGE PlayerState : public CBonusSystemNode
  130. {
  131. public:
  132. PlayerColor color;
  133. bool human; //true if human controlled player, false for AI
  134. ObjectInstanceID currentSelection; //id of hero/town, 0xffffffff if none
  135. TeamID team;
  136. TResources resources;
  137. std::vector<ConstTransitivePtr<CGHeroInstance> > heroes;
  138. std::vector<ConstTransitivePtr<CGTownInstance> > towns;
  139. std::vector<ConstTransitivePtr<CGHeroInstance> > availableHeroes; //heroes available in taverns
  140. std::vector<ConstTransitivePtr<CGDwelling> > dwellings; //used for town growth
  141. std::vector<QuestInfo> quests; //store info about all received quests
  142. bool enteredWinningCheatCode, enteredLosingCheatCode; //if true, this player has entered cheat codes for loss / victory
  143. EPlayerStatus::EStatus status;
  144. boost::optional<ui8> daysWithoutCastle;
  145. PlayerState();
  146. std::string nodeName() const override;
  147. template <typename Handler> void serialize(Handler &h, const int version)
  148. {
  149. h & color & human & currentSelection & team & resources & status;
  150. h & heroes & towns & availableHeroes & dwellings;
  151. h & getBonusList(); //FIXME FIXME FIXME
  152. h & status & daysWithoutCastle;
  153. h & enteredLosingCheatCode & enteredWinningCheatCode;
  154. h & static_cast<CBonusSystemNode&>(*this);
  155. }
  156. };
  157. struct DLL_LINKAGE TeamState : public CBonusSystemNode
  158. {
  159. public:
  160. TeamID id; //position in gameState::teams
  161. std::set<PlayerColor> players; // members of this team
  162. std::vector<std::vector<std::vector<ui8> > > fogOfWarMap; //true - visible, false - hidden
  163. TeamState();
  164. template <typename Handler> void serialize(Handler &h, const int version)
  165. {
  166. h & id & players & fogOfWarMap;
  167. h & static_cast<CBonusSystemNode&>(*this);
  168. }
  169. };
  170. struct UpgradeInfo
  171. {
  172. CreatureID oldID; //creature to be upgraded
  173. std::vector<CreatureID> newID; //possible upgrades
  174. std::vector<TResources> cost; // cost[upgrade_serial] -> set of pairs<resource_ID,resource_amount>; cost is for single unit (not entire stack)
  175. UpgradeInfo(){oldID = CreatureID::NONE;};
  176. };
  177. struct DLL_LINKAGE CGPathNode
  178. {
  179. enum EAccessibility
  180. {
  181. NOT_SET = 0,
  182. ACCESSIBLE = 1, //tile can be entered and passed
  183. VISITABLE, //tile can be entered as the last tile in path
  184. BLOCKVIS, //visitable from neighbouring tile but not passable
  185. BLOCKED //tile can't be entered nor visited
  186. };
  187. EAccessibility accessible;
  188. ui8 land;
  189. ui8 turns; //how many turns we have to wait before reachng the tile - 0 means current turn
  190. ui32 moveRemains; //remaining tiles after hero reaches the tile
  191. CGPathNode * theNodeBefore;
  192. int3 coord; //coordinates
  193. CGPathNode();
  194. bool reachable() const;
  195. };
  196. struct DLL_LINKAGE CGPath
  197. {
  198. std::vector<CGPathNode> nodes; //just get node by node
  199. int3 startPos() const; // start point
  200. int3 endPos() const; //destination point
  201. void convert(ui8 mode); //mode=0 -> from 'manifest' to 'object'
  202. };
  203. struct DLL_LINKAGE CPathsInfo
  204. {
  205. bool isValid;
  206. const CGHeroInstance *hero;
  207. int3 hpos;
  208. int3 sizes;
  209. CGPathNode ***nodes; //[w][h][level]
  210. bool getPath(const int3 &dst, CGPath &out);
  211. CPathsInfo(const int3 &Sizes);
  212. ~CPathsInfo();
  213. };
  214. struct DLL_EXPORT DuelParameters
  215. {
  216. ETerrainType terType;
  217. BFieldType bfieldType;
  218. struct DLL_EXPORT SideSettings
  219. {
  220. struct DLL_EXPORT StackSettings
  221. {
  222. CreatureID type;
  223. si32 count;
  224. template <typename Handler> void serialize(Handler &h, const int version)
  225. {
  226. h & type & count;
  227. }
  228. StackSettings();
  229. StackSettings(CreatureID Type, si32 Count);
  230. } stacks[GameConstants::ARMY_SIZE];
  231. si32 heroId; //-1 if none
  232. std::vector<si32> heroPrimSkills; //may be empty
  233. std::map<si32, CArtifactInstance*> artifacts;
  234. std::vector<std::pair<si32, si8> > heroSecSkills; //may be empty; pairs <id, level>, level [0-3]
  235. std::set<SpellID> spells;
  236. SideSettings();
  237. template <typename Handler> void serialize(Handler &h, const int version)
  238. {
  239. h & stacks & heroId & heroPrimSkills & artifacts & heroSecSkills & spells;
  240. }
  241. } sides[2];
  242. std::vector<shared_ptr<CObstacleInstance> > obstacles;
  243. static DuelParameters fromJSON(const std::string &fname);
  244. struct CusomCreature
  245. {
  246. int id;
  247. int attack, defense, dmg, HP, speed, shoots;
  248. CusomCreature()
  249. {
  250. id = attack = defense = dmg = HP = speed = shoots = -1;
  251. }
  252. template <typename Handler> void serialize(Handler &h, const int version)
  253. {
  254. h & id & attack & defense & dmg & HP & speed & shoots;
  255. }
  256. };
  257. std::vector<CusomCreature> creatures;
  258. DuelParameters();
  259. template <typename Handler> void serialize(Handler &h, const int version)
  260. {
  261. h & terType & bfieldType & sides & obstacles & creatures;
  262. }
  263. };
  264. class CPathfinder : private CGameInfoCallback
  265. {
  266. private:
  267. bool useSubterraneanGates;
  268. bool allowEmbarkAndDisembark;
  269. CPathsInfo &out;
  270. const CGHeroInstance *hero;
  271. const std::vector<std::vector<std::vector<ui8> > > &FoW;
  272. std::list<CGPathNode*> mq; //BFS queue -> nodes to be checked
  273. int3 curPos;
  274. CGPathNode *cp; //current (source) path node -> we took it from the queue
  275. CGPathNode *dp; //destination node -> it's a neighbour of cp that we consider
  276. const TerrainTile *ct, *dt; //tile info for both nodes
  277. ui8 useEmbarkCost; //0 - usual movement; 1 - embark; 2 - disembark
  278. int destTopVisObjID;
  279. CGPathNode *getNode(const int3 &coord);
  280. void initializeGraph();
  281. bool goodForLandSeaTransition(); //checks if current move will be between sea<->land. If so, checks it legality (returns false if movement is not possible) and sets useEmbarkCost
  282. CGPathNode::EAccessibility evaluateAccessibility(const TerrainTile *tinfo) const;
  283. bool canMoveBetween(const int3 &a, const int3 &b) const; //checks only for visitable objects that may make moving between tiles impossible, not other conditions (like tiles itself accessibility)
  284. public:
  285. CPathfinder(CPathsInfo &_out, CGameState *_gs, const CGHeroInstance *_hero);
  286. void calculatePaths(int3 src = int3(-1,-1,-1), int movement = -1); //calculates possible paths for hero, by default uses current hero position and movement left; returns pointer to newly allocated CPath or nullptr if path does not exists
  287. };
  288. struct BattleInfo;
  289. class DLL_LINKAGE EVictoryLossCheckResult
  290. {
  291. public:
  292. static const EVictoryLossCheckResult NO_VICTORY_OR_LOSS;
  293. static const EVictoryLossCheckResult VICTORY_STANDARD;
  294. static const EVictoryLossCheckResult VICTORY_SPECIAL;
  295. static const EVictoryLossCheckResult LOSS_STANDARD_HEROES_AND_TOWNS;
  296. static const EVictoryLossCheckResult LOSS_STANDARD_TOWNS_AND_TIME_OVER;
  297. static const EVictoryLossCheckResult LOSS_SPECIAL;
  298. EVictoryLossCheckResult();
  299. bool operator==(EVictoryLossCheckResult const & other) const;
  300. bool operator!=(EVictoryLossCheckResult const & other) const;
  301. bool victory() const;
  302. bool loss() const;
  303. std::string toString() const;
  304. template <typename Handler> void serialize(Handler &h, const int version)
  305. {
  306. h & intValue;
  307. }
  308. private:
  309. EVictoryLossCheckResult(si32 intValue);
  310. si32 intValue;
  311. };
  312. DLL_LINKAGE std::ostream & operator<<(std::ostream & os, const EVictoryLossCheckResult & victoryLossCheckResult);
  313. class DLL_LINKAGE CGameState : public CNonConstInfoCallback
  314. {
  315. public:
  316. struct DLL_LINKAGE HeroesPool
  317. {
  318. std::map<ui32, ConstTransitivePtr<CGHeroInstance> > heroesPool; //[subID] - heroes available to buy; nullptr if not available
  319. std::map<ui32,ui8> pavailable; // [subid] -> which players can recruit hero (binary flags)
  320. CGHeroInstance * pickHeroFor(bool native, PlayerColor player, const CTown *town, std::map<ui32, ConstTransitivePtr<CGHeroInstance> > &available, const CHeroClass *bannedClass = nullptr) const;
  321. template <typename Handler> void serialize(Handler &h, const int version)
  322. {
  323. h & heroesPool & pavailable;
  324. }
  325. } hpool; //we have here all heroes available on this map that are not hired
  326. CGameState();
  327. virtual ~CGameState();
  328. void init(StartInfo * si);
  329. ConstTransitivePtr<StartInfo> scenarioOps, initialOpts; //second one is a copy of settings received from pregame (not randomized)
  330. PlayerColor currentPlayer; //ID of player currently having turn
  331. ConstTransitivePtr<BattleInfo> curB; //current battle
  332. ui32 day; //total number of days in game
  333. ConstTransitivePtr<CMap> map;
  334. std::map<PlayerColor, PlayerState> players;
  335. std::map<TeamID, TeamState> teams;
  336. CBonusSystemNode globalEffects;
  337. boost::shared_mutex *mx;
  338. void giveHeroArtifact(CGHeroInstance *h, ArtifactID aid);
  339. void apply(CPack *pack);
  340. BFieldType battleGetBattlefieldType(int3 tile) const;
  341. UpgradeInfo getUpgradeInfo(const CStackInstance &stack);
  342. PlayerRelations::PlayerRelations getPlayerRelations(PlayerColor color1, PlayerColor color2);
  343. bool checkForVisitableDir(const int3 & src, const int3 & dst) const; //check if src tile is visitable from dst tile
  344. bool checkForVisitableDir(const int3 & src, const TerrainTile *pom, const int3 & dst) const; //check if src tile is visitable from dst tile
  345. void calculatePaths(const CGHeroInstance *hero, CPathsInfo &out, int3 src = int3(-1,-1,-1), int movement = -1); //calculates possible paths for hero, by default uses current hero position and movement left; returns pointer to newly allocated CPath or nullptr if path does not exists
  346. int3 guardingCreaturePosition (int3 pos) const;
  347. std::vector<CGObjectInstance*> guardingCreatures (int3 pos) const;
  348. EVictoryLossCheckResult checkForVictoryAndLoss(PlayerColor player) const;
  349. void obtainPlayersStats(SThievesGuildInfo & tgi, int level); //fills tgi with info about other players that is available at given level of thieves' guild
  350. std::map<ui32, ConstTransitivePtr<CGHeroInstance> > unusedHeroesFromPool(); //heroes pool without heroes that are available in taverns
  351. BattleInfo * setupBattle(int3 tile, const CArmedInstance *armies[2], const CGHeroInstance * heroes[2], bool creatureBank, const CGTownInstance *town);
  352. bool isVisible(int3 pos, PlayerColor player);
  353. bool isVisible(const CGObjectInstance *obj, boost::optional<PlayerColor> player);
  354. void getNeighbours(const TerrainTile &srct, int3 tile, std::vector<int3> &vec, const boost::logic::tribool &onLand, bool limitCoastSailing);
  355. int getMovementCost(const CGHeroInstance *h, const int3 &src, const int3 &dest, int remainingMovePoints=-1, bool checkLast=true);
  356. int getDate(Date::EDateType mode=Date::DAY) const; //mode=0 - total days in game, mode=1 - day of week, mode=2 - current week, mode=3 - current month
  357. template <typename Handler> void serialize(Handler &h, const int version)
  358. {
  359. h & scenarioOps & initialOpts & currentPlayer & day & map & players & teams & hpool & globalEffects;
  360. BONUS_TREE_DESERIALIZATION_FIX
  361. }
  362. private:
  363. // ----- initialization -----
  364. void initNewGame();
  365. void initCampaign();
  366. void initDuel();
  367. void checkMapChecksum();
  368. void initGrailPosition();
  369. void initRandomFactionsForPlayers();
  370. void randomizeMapObjects();
  371. void randomizeObject(CGObjectInstance *cur);
  372. void initPlayerStates();
  373. void placeCampaignHeroes();
  374. const CCampaignScenario * getCampaignScenarioForCrossoverHeroes() const;
  375. std::vector<CGHeroInstance *> prepareCrossoverHeroes(const CCampaignScenario * campaignScenario);
  376. // returns heroes and placeholders in where heroes will be put
  377. std::vector<std::pair<CGHeroInstance*, ObjectInstanceID> > generateCampaignHeroesToReplace(std::vector<CGHeroInstance *> & crossoverHeroes);
  378. void replaceHeroesPlaceholders(const std::vector<std::pair<CGHeroInstance*, ObjectInstanceID> > &campHeroReplacements);
  379. void placeStartingHeroes();
  380. void placeStartingHero(PlayerColor playerColor, HeroTypeID heroTypeId, int3 townPos);
  381. void initStartingResources();
  382. void initHeroes();
  383. void giveCampaignBonusToHero(CGHeroInstance * hero);
  384. void initFogOfWar();
  385. void initStartingBonus();
  386. void initTowns();
  387. void initMapObjects();
  388. void initVisitingAndGarrisonedHeroes();
  389. // ----- victory, loss condition checks -----
  390. EVictoryLossCheckResult checkForVictory(PlayerColor player) const; //checks if given player is winner
  391. EVictoryLossCheckResult checkForLoss(PlayerColor player) const; //checks if given player is loser
  392. PlayerColor checkForStandardWin() const; //returns color of player that accomplished standard victory conditions or 255 (NEUTRAL) if no winner
  393. bool checkForStandardLoss(PlayerColor player) const; //checks if given player lost the game
  394. // ----- bonus system handling -----
  395. void buildBonusSystemTree();
  396. void attachArmedObjects();
  397. void buildGlobalTeamPlayerTree();
  398. void deserializationFix();
  399. // ---- misc helpers -----
  400. bool isUsedHero(HeroTypeID hid) const; //looks in heroes and prisons
  401. std::set<HeroTypeID> getUnusedAllowedHeroes(bool alsoIncludeNotAllowed = false) const;
  402. std::pair<Obj,int> pickObject(CGObjectInstance *obj); //chooses type of object to be randomized, returns <type, subtype>
  403. int pickUnusedHeroTypeRandomly(PlayerColor owner) const; // picks a unused hero type randomly
  404. int pickNextHeroType(PlayerColor owner) const; // picks next free hero type of the H3 hero init sequence -> chosen starting hero, then unused hero type randomly
  405. friend class CCallback;
  406. friend class CClient;
  407. friend class IGameCallback;
  408. friend class CMapHandler;
  409. friend class CGameHandler;
  410. };
  411. struct DLL_LINKAGE QuestInfo //universal interface for human and AI
  412. {
  413. const CQuest * quest;
  414. const CGObjectInstance * obj; //related object, most likely Seer Hut
  415. int3 tile;
  416. QuestInfo(){};
  417. QuestInfo (const CQuest * Quest, const CGObjectInstance * Obj, int3 Tile) :
  418. quest (Quest), obj (Obj), tile (Tile){};
  419. //FIXME: assignment operator should return QuestInfo &
  420. bool operator= (const QuestInfo &qi)
  421. {
  422. quest = qi.quest;
  423. obj = qi.obj;
  424. tile = qi.tile;
  425. return true;
  426. }
  427. bool operator== (const QuestInfo & qi) const
  428. {
  429. return (quest == qi.quest && obj == qi.obj);
  430. }
  431. //std::vector<std::string> > texts //allow additional info for quest log?
  432. template <typename Handler> void serialize(Handler &h, const int version)
  433. {
  434. h & quest & obj & tile;
  435. }
  436. };