CGameState.h 18 KB

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