CGameState.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  1. #pragma once
  2. //#ifndef _MSC_VER
  3. #include "CCreatureHandler.h"
  4. #include "VCMI_Lib.h"
  5. #include "Map/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. /*
  15. * CGameState.h, part of VCMI engine
  16. *
  17. * Authors: listed in file AUTHORS in main folder
  18. *
  19. * License: GNU General Public License v2.0 or later
  20. * Full text of license available in license.txt file, in main folder
  21. *
  22. */
  23. class CTown;
  24. class CScriptCallback;
  25. class CCallback;
  26. class IGameCallback;
  27. class CLuaCallback;
  28. class CCPPObjectScript;
  29. class CCreatureSet;
  30. class CStack;
  31. class CQuest;
  32. class CGHeroInstance;
  33. class CGTownInstance;
  34. class CArmedInstance;
  35. class CGDwelling;
  36. class CObjectScript;
  37. class CGObjectInstance;
  38. class CCreature;
  39. class CMap;
  40. struct StartInfo;
  41. struct SDL_Surface;
  42. class CMapHandler;
  43. class CPathfinder;
  44. struct SetObjectProperty;
  45. struct MetaString;
  46. struct CPack;
  47. class CSpell;
  48. struct TerrainTile;
  49. class CHeroClass;
  50. class CCampaign;
  51. class CCampaignState;
  52. class IModableArt;
  53. class CGGarrison;
  54. class CGameInfo;
  55. struct QuestInfo;
  56. class CQuest;
  57. namespace boost
  58. {
  59. class shared_mutex;
  60. }
  61. //numbers of creatures are exact numbers if detailed else they are quantity ids (0 - a few, 1 - several and so on; additionally -1 - unknown)
  62. struct ArmyDescriptor : public std::map<TSlot, CStackBasicDescriptor>
  63. {
  64. bool isDetailed;
  65. DLL_LINKAGE ArmyDescriptor(const CArmedInstance *army, bool detailed); //not detailed -> quantity ids as count
  66. DLL_LINKAGE ArmyDescriptor();
  67. DLL_LINKAGE int getStrength() const;
  68. };
  69. struct DLL_LINKAGE InfoAboutArmy
  70. {
  71. ui8 owner;
  72. std::string name;
  73. ArmyDescriptor army;
  74. InfoAboutArmy();
  75. InfoAboutArmy(const CArmedInstance *Army, bool detailed);
  76. void initFromArmy(const CArmedInstance *Army, bool detailed);
  77. };
  78. struct DLL_LINKAGE InfoAboutHero : public InfoAboutArmy
  79. {
  80. private:
  81. void assign(const InfoAboutHero & iah);
  82. public:
  83. struct DLL_LINKAGE Details
  84. {
  85. std::vector<si32> primskills;
  86. si32 mana, luck, morale;
  87. } *details;
  88. const CHeroClass *hclass;
  89. int portrait;
  90. InfoAboutHero();
  91. InfoAboutHero(const InfoAboutHero & iah);
  92. InfoAboutHero(const CGHeroInstance *h, bool detailed);
  93. ~InfoAboutHero();
  94. InfoAboutHero & operator=(const InfoAboutHero & iah);
  95. void initFromHero(const CGHeroInstance *h, bool detailed);
  96. };
  97. /// Struct which holds a int information about a town
  98. struct DLL_LINKAGE InfoAboutTown : public InfoAboutArmy
  99. {
  100. struct DLL_LINKAGE Details
  101. {
  102. si32 hallLevel, goldIncome;
  103. bool customRes;
  104. bool garrisonedHero;
  105. } *details;
  106. CTown *tType;
  107. si32 built;
  108. si32 fortLevel; //0 - none
  109. InfoAboutTown();
  110. InfoAboutTown(const CGTownInstance *t, bool detailed);
  111. ~InfoAboutTown();
  112. void initFromTown(const CGTownInstance *t, bool detailed);
  113. };
  114. // typedef si32 TResourceUnit;
  115. // typedef std::vector<si32> TResourceVector;
  116. // typedef std::set<si32> TResourceSet;
  117. struct DLL_LINKAGE SThievesGuildInfo
  118. {
  119. std::vector<TPlayerColor> playerColors; //colors of players that are in-game
  120. std::vector< std::vector< TPlayerColor > > numOfTowns, numOfHeroes, gold, woodOre, mercSulfCrystGems, obelisks, artifacts, army, income; // [place] -> [colours of players]
  121. std::map<TPlayerColor, InfoAboutHero> colorToBestHero; //maps player's color to his best heros'
  122. std::map<TPlayerColor, EAiTactic::EAiTactic> personality; // color to personality // ai tactic
  123. std::map<TPlayerColor, si32> bestCreature; // color to ID // id or -1 if not known
  124. // template <typename Handler> void serialize(Handler &h, const int version)
  125. // {
  126. // h & playerColors & numOfTowns & numOfHeroes & gold & woodOre & mercSulfCrystGems & obelisks & artifacts & army & income;
  127. // h & colorToBestHero & personality & bestCreature;
  128. // }
  129. };
  130. struct DLL_LINKAGE PlayerState : public CBonusSystemNode
  131. {
  132. public:
  133. enum EStatus {INGAME, LOSER, WINNER};
  134. TPlayerColor color;
  135. ui8 human; //true if human controlled player, false for AI
  136. ui32 currentSelection; //id of hero/town, 0xffffffff if none
  137. ui8 team;
  138. TResources resources;
  139. std::vector<ConstTransitivePtr<CGHeroInstance> > heroes;
  140. std::vector<ConstTransitivePtr<CGTownInstance> > towns;
  141. std::vector<ConstTransitivePtr<CGHeroInstance> > availableHeroes; //heroes available in taverns
  142. std::vector<ConstTransitivePtr<CGDwelling> > dwellings; //used for town growth
  143. std::vector<QuestInfo> quests; //store info about all received quests
  144. ui8 enteredWinningCheatCode, enteredLosingCheatCode; //if true, this player has entered cheat codes for loss / victory
  145. ui8 status; //0 - in game, 1 - loser, 2 - winner <- uses EStatus enum
  146. ui8 daysWithoutCastle;
  147. PlayerState();
  148. std::string nodeName() const OVERRIDE;
  149. //override
  150. //void getParents(TCNodes &out, const CBonusSystemNode *root = NULL) const;
  151. //void getBonuses(BonusList &out, const CSelector &selector, const CBonusSystemNode *root = NULL) const;
  152. template <typename Handler> void serialize(Handler &h, const int version)
  153. {
  154. h & color & human & currentSelection & team & resources & status;
  155. h & heroes & towns & availableHeroes & dwellings;
  156. h & getBonusList(); //FIXME FIXME FIXME
  157. h & status & daysWithoutCastle;
  158. h & enteredLosingCheatCode & enteredWinningCheatCode;
  159. h & static_cast<CBonusSystemNode&>(*this);
  160. }
  161. };
  162. struct DLL_LINKAGE TeamState : public CBonusSystemNode
  163. {
  164. public:
  165. ui8 id; //position in gameState::teams
  166. std::set<TPlayerColor> players; // members of this team
  167. std::vector<std::vector<std::vector<ui8> > > fogOfWarMap; //true - visible, false - hidden
  168. TeamState();
  169. template <typename Handler> void serialize(Handler &h, const int version)
  170. {
  171. h & id & players & fogOfWarMap;
  172. h & static_cast<CBonusSystemNode&>(*this);
  173. }
  174. };
  175. struct UpgradeInfo
  176. {
  177. int oldID; //creature to be upgraded
  178. std::vector<int> newID; //possible upgrades
  179. std::vector<TResources> cost; // cost[upgrade_serial] -> set of pairs<resource_ID,resource_amount>; cost is for single unit (not entire stack)
  180. UpgradeInfo(){oldID = -1;};
  181. };
  182. struct CPathNode
  183. {
  184. bool accessible; //true if a hero can be on this node
  185. int dist; //distance from the first node of searching; -1 is infinity
  186. CPathNode * theNodeBefore;
  187. int3 coord; //coordiantes
  188. bool visited;
  189. };
  190. struct DLL_LINKAGE CGPathNode
  191. {
  192. enum EAccessibility
  193. {
  194. ACCESSIBLE=1, //tile can be entered and passed
  195. VISITABLE, //tile can be entered as the last tile in path
  196. BLOCKVIS, //visitable from neighbouring tile but not passable
  197. BLOCKED //tile can't be entered nor visited
  198. };
  199. ui8 accessible; //the enum above
  200. ui8 land;
  201. ui8 turns;
  202. ui32 moveRemains;
  203. CGPathNode * theNodeBefore;
  204. int3 coord; //coordinates
  205. CGPathNode();
  206. bool reachable() const;
  207. };
  208. struct DLL_LINKAGE CPath
  209. {
  210. std::vector<CPathNode> nodes; //just get node by node
  211. int3 startPos() const; // start point
  212. int3 endPos() const; //destination point
  213. void convert(ui8 mode); //mode=0 -> from 'manifest' to 'object'
  214. };
  215. struct DLL_LINKAGE CGPath
  216. {
  217. std::vector<CGPathNode> nodes; //just get node by node
  218. int3 startPos() const; // start point
  219. int3 endPos() const; //destination point
  220. void convert(ui8 mode); //mode=0 -> from 'manifest' to 'object'
  221. };
  222. struct DLL_LINKAGE CPathsInfo
  223. {
  224. bool isValid;
  225. const CGHeroInstance *hero;
  226. int3 hpos;
  227. int3 sizes;
  228. CGPathNode ***nodes; //[w][h][level]
  229. bool getPath(const int3 &dst, CGPath &out);
  230. CPathsInfo(const int3 &Sizes);
  231. ~CPathsInfo();
  232. };
  233. struct DLL_EXPORT DuelParameters
  234. {
  235. si32 terType, bfieldType;
  236. struct DLL_EXPORT SideSettings
  237. {
  238. struct DLL_EXPORT StackSettings
  239. {
  240. si32 type;
  241. si32 count;
  242. template <typename Handler> void serialize(Handler &h, const int version)
  243. {
  244. h & type & count;
  245. }
  246. StackSettings();
  247. StackSettings(si32 Type, si32 Count);
  248. } stacks[GameConstants::ARMY_SIZE];
  249. si32 heroId; //-1 if none
  250. std::vector<si32> heroPrimSkills; //may be empty
  251. std::map<si32, CArtifactInstance*> artifacts;
  252. std::vector<std::pair<si32, si8> > heroSecSkills; //may be empty; pairs <id, level>, level [0-3]
  253. std::set<si32> spells;
  254. SideSettings();
  255. template <typename Handler> void serialize(Handler &h, const int version)
  256. {
  257. h & stacks & heroId & heroPrimSkills & artifacts & heroSecSkills & spells;
  258. }
  259. } sides[2];
  260. std::vector<shared_ptr<CObstacleInstance> > obstacles;
  261. static DuelParameters fromJSON(const std::string &fname);
  262. struct CusomCreature
  263. {
  264. int id;
  265. int attack, defense, dmg, HP, speed, shoots;
  266. CusomCreature()
  267. {
  268. id = attack = defense = dmg = HP = speed = shoots = -1;
  269. }
  270. template <typename Handler> void serialize(Handler &h, const int version)
  271. {
  272. h & id & attack & defense & dmg & HP & speed & shoots;
  273. }
  274. };
  275. std::vector<CusomCreature> creatures;
  276. DuelParameters();
  277. template <typename Handler> void serialize(Handler &h, const int version)
  278. {
  279. h & terType & bfieldType & sides & obstacles & creatures;
  280. }
  281. };
  282. class CPathfinder : private CGameInfoCallback
  283. {
  284. private:
  285. bool useSubterraneanGates;
  286. bool allowEmbarkAndDisembark;
  287. CPathsInfo &out;
  288. const CGHeroInstance *hero;
  289. const std::vector<std::vector<std::vector<ui8> > > &FoW;
  290. std::list<CGPathNode*> mq; //BFS queue -> nodes to be checked
  291. int3 curPos;
  292. CGPathNode *cp; //current (source) path node -> we took it from the queue
  293. CGPathNode *dp; //destination node -> it's a neighbour of cp that we consider
  294. const TerrainTile *ct, *dt; //tile info for both nodes
  295. ui8 useEmbarkCost; //0 - usual movement; 1 - embark; 2 - disembark
  296. int destTopVisObjID;
  297. CGPathNode *getNode(const int3 &coord);
  298. void initializeGraph();
  299. 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
  300. CGPathNode::EAccessibility evaluateAccessibility(const TerrainTile *tinfo) const;
  301. 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)
  302. bool canStepOntoDst() const;
  303. public:
  304. CPathfinder(CPathsInfo &_out, CGameState *_gs, const CGHeroInstance *_hero);
  305. 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 NULL if path does not exists
  306. };
  307. struct BattleInfo;
  308. class DLL_LINKAGE CGameState : public CNonConstInfoCallback
  309. {
  310. public:
  311. ConstTransitivePtr<StartInfo> scenarioOps, initialOpts; //second one is a copy of settings received from pregame (not randomized)
  312. ui8 currentPlayer; //ID of player currently having turn
  313. ConstTransitivePtr<BattleInfo> curB; //current battle
  314. ui32 day; //total number of days in game
  315. ConstTransitivePtr<CMap> map;
  316. bmap<TPlayerColor, PlayerState> players;
  317. bmap<TPlayerColor, TeamState> teams;
  318. CBonusSystemNode globalEffects;
  319. bmap<const CGHeroInstance*, const CGObjectInstance*> ongoingVisits;
  320. struct DLL_LINKAGE HeroesPool
  321. {
  322. bmap<ui32, ConstTransitivePtr<CGHeroInstance> > heroesPool; //[subID] - heroes available to buy; NULL if not available
  323. bmap<ui32,ui8> pavailable; // [subid] -> which players can recruit hero (binary flags)
  324. CGHeroInstance * pickHeroFor(bool native, TPlayerColor player, const CTown *town, bmap<ui32, ConstTransitivePtr<CGHeroInstance> > &available, const CHeroClass *bannedClass = NULL) const;
  325. template <typename Handler> void serialize(Handler &h, const int version)
  326. {
  327. h & heroesPool & pavailable;
  328. }
  329. } hpool; //we have here all heroes available on this map that are not hired
  330. boost::shared_mutex *mx;
  331. void init(StartInfo * si);
  332. void initDuel();
  333. void randomizeObject(CGObjectInstance *cur);
  334. std::pair<int,int> pickObject(CGObjectInstance *obj); //chooses type of object to be randomized, returns <type, subtype>
  335. int pickHero(int owner);
  336. void giveHeroArtifact(CGHeroInstance *h, int aid);
  337. void apply(CPack *pack);
  338. int battleGetBattlefieldType(int3 tile) const;// 1. sand/shore 2. sand/mesas 3. dirt/birches 4. dirt/hills 5. dirt/pines 6. grass/hills 7. grass/pines 8. lava 9. magic plains 10. snow/mountains 11. snow/trees 12. subterranean 13. swamp/trees 14. fiery fields 15. rock lands 16. magic clouds 17. lucid pools 18. holy ground 19. clover field 20. evil fog 21. "favourable winds" text on magic plains background 22. cursed ground 23. rough 24. ship to ship 25. ship
  339. UpgradeInfo getUpgradeInfo(const CStackInstance &stack);
  340. int getPlayerRelations(ui8 color1, ui8 color2);// 0 = enemy, 1 = ally, 2 = same player
  341. bool checkForVisitableDir(const int3 & src, const int3 & dst) const; //check if src tile is visitable from dst tile
  342. bool checkForVisitableDir(const int3 & src, const TerrainTile *pom, const int3 & dst) const; //check if src tile is visitable from dst tile
  343. bool getPath(int3 src, int3 dest, const CGHeroInstance * hero, CPath &ret); //calculates path between src and dest; returns pointer to newly allocated CPath or NULL if path does not exists
  344. 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 NULL if path does not exists
  345. int3 guardingCreaturePosition (int3 pos) const;
  346. std::vector<CGObjectInstance*> guardingCreatures (int3 pos) const;
  347. int victoryCheck(ui8 player) const; //checks if given player is winner; -1 if std victory, 1 if special victory, 0 else
  348. int lossCheck(ui8 player) const; //checks if given player is loser; -1 if std loss, 1 if special, 0 else
  349. ui8 checkForStandardWin() const; //returns color of player that accomplished standard victory conditions or 255 if no winner
  350. bool checkForStandardLoss(ui8 player) const; //checks if given player lost the game
  351. void obtainPlayersStats(SThievesGuildInfo & tgi, int level); //fills tgi with info about other players that is available at given level of thieves' guild
  352. bmap<ui32, ConstTransitivePtr<CGHeroInstance> > unusedHeroesFromPool(); //heroes pool without heroes that are available in taverns
  353. BattleInfo * setupBattle(int3 tile, const CArmedInstance *armies[2], const CGHeroInstance * heroes[2], bool creatureBank, const CGTownInstance *town);
  354. void buildBonusSystemTree();
  355. void attachArmedObjects();
  356. void buildGlobalTeamPlayerTree();
  357. void deserializationFix();
  358. bool isVisible(int3 pos, int player);
  359. bool isVisible(const CGObjectInstance *obj, int player);
  360. CGameState(); //c-tor
  361. virtual ~CGameState(); //d-tor
  362. void getNeighbours(const TerrainTile &srct, int3 tile, std::vector<int3> &vec, const boost::logic::tribool &onLand, bool limitCoastSailing);
  363. int getMovementCost(const CGHeroInstance *h, const int3 &src, const int3 &dest, int remainingMovePoints=-1, bool checkLast=true);
  364. int getDate(int mode=0) const; //mode=0 - total days in game, mode=1 - day of week, mode=2 - current week, mode=3 - current month
  365. template <typename Handler> void serialize(Handler &h, const int version)
  366. {
  367. h & scenarioOps & initialOpts & currentPlayer & day & map & players & teams & hpool & globalEffects;
  368. BONUS_TREE_DESERIALIZATION_FIX
  369. }
  370. friend class CCallback;
  371. friend class CLuaCallback;
  372. friend class CClient;
  373. friend void initGameState(CMap * map, CGameInfo * cgi);
  374. friend class IGameCallback;
  375. friend class CMapHandler;
  376. friend class CGameHandler;
  377. };
  378. struct DLL_LINKAGE QuestInfo //universal interface for human and AI
  379. {
  380. const CQuest * quest;
  381. const CGObjectInstance * obj; //related object, most likely Seer Hut
  382. int3 tile;
  383. QuestInfo(){};
  384. QuestInfo (const CQuest * Quest, const CGObjectInstance * Obj, int3 Tile) :
  385. quest (Quest), obj (Obj), tile (Tile){};
  386. bool operator= (const QuestInfo &qi)
  387. {
  388. quest = qi.quest;
  389. obj = qi.obj;
  390. tile = qi.tile;
  391. return true;
  392. }
  393. bool operator== (const QuestInfo & qi) const
  394. {
  395. return (quest == qi.quest && obj == qi.obj);
  396. }
  397. //std::vector<std::string> > texts //allow additional info for quest log?
  398. template <typename Handler> void serialize(Handler &h, const int version)
  399. {
  400. h & quest & obj & tile;
  401. }
  402. };