CGameState.h 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463
  1. #ifndef __CGAMESTATE_H__
  2. #define __CGAMESTATE_H__
  3. #include "../global.h"
  4. #include <cassert>
  5. #ifndef _MSC_VER
  6. #include "../hch/CCreatureHandler.h"
  7. #include "VCMI_Lib.h"
  8. #include "map.h"
  9. #endif
  10. #include <set>
  11. #include <vector>
  12. #include <list>
  13. #include "HeroBonus.h"
  14. #include "CCreatureSet.h"
  15. #ifdef _WIN32
  16. #include <tchar.h>
  17. #else
  18. #include "../tchar_amigaos4.h"
  19. #endif
  20. /*
  21. * CGameState.h, part of VCMI engine
  22. *
  23. * Authors: listed in file AUTHORS in main folder
  24. *
  25. * License: GNU General Public License v2.0 or later
  26. * Full text of license available in license.txt file, in main folder
  27. *
  28. */
  29. class CTown;
  30. class CScriptCallback;
  31. class CCallback;
  32. class IGameCallback;
  33. class CLuaCallback;
  34. class CCPPObjectScript;
  35. class CCreatureSet;
  36. class CStack;
  37. class CGHeroInstance;
  38. class CGTownInstance;
  39. class CArmedInstance;
  40. class CGDwelling;
  41. class CGDefInfo;
  42. class CObjectScript;
  43. class CGObjectInstance;
  44. class CCreature;
  45. struct Mapa;
  46. struct StartInfo;
  47. struct SDL_Surface;
  48. class CMapHandler;
  49. class CPathfinder;
  50. struct SetObjectProperty;
  51. struct MetaString;
  52. struct CPack;
  53. class CSpell;
  54. struct TerrainTile;
  55. class CHeroClass;
  56. class CCampaign;
  57. namespace boost
  58. {
  59. class shared_mutex;
  60. }
  61. struct DLL_EXPORT InfoAboutHero
  62. {
  63. private:
  64. void assign(const InfoAboutHero & iah);
  65. public:
  66. struct DLL_EXPORT Details
  67. {
  68. std::vector<int> primskills;
  69. int mana, luck, morale;
  70. } *details;
  71. char owner;
  72. const CHeroClass *hclass;
  73. std::string name;
  74. int portrait;
  75. CCreatureSet army; //numbers of creatures are exact numbers if detailed else they are quantity ids (0 - a few, 1 - several and so on)
  76. InfoAboutHero();
  77. InfoAboutHero(const InfoAboutHero & iah);
  78. InfoAboutHero & operator=(const InfoAboutHero & iah);
  79. ~InfoAboutHero();
  80. void initFromHero(const CGHeroInstance *h, bool detailed);
  81. };
  82. struct DLL_EXPORT SThievesGuildInfo
  83. {
  84. std::vector<ui8> playerColors; //colors of players that are in-game
  85. std::vector< std::list< ui8 > > numOfTowns, numOfHeroes, gold, woodOre, mercSulfCrystGems, obelisks, artifacts, army, income; // [place] -> [colours of players]
  86. std::map<ui8, InfoAboutHero> colorToBestHero; //maps player's color to his best heros'
  87. std::map<ui8, si8> personality; // color to personality // -1 - human, AI -> (00 - random, 01 - warrior, 02 - builder, 03 - explorer)
  88. std::map<ui8, si32> bestCreature; // color to ID // id or -1 if not known
  89. // template <typename Handler> void serialize(Handler &h, const int version)
  90. // {
  91. // h & playerColors & numOfTowns & numOfHeroes & gold & woodOre & mercSulfCrystGems & obelisks & artifacts & army & income;
  92. // h & colorToBestHero & personality & bestCreature;
  93. // }
  94. };
  95. struct DLL_EXPORT PlayerState : public CBonusSystemNode
  96. {
  97. public:
  98. enum EStatus {INGAME, LOSER, WINNER};
  99. ui8 color, serial;
  100. ui8 human; //true if human controlled player, false for AI
  101. ui32 currentSelection; //id of hero/town, 0xffffffff if none
  102. std::vector<std::vector<std::vector<ui8> > > fogOfWarMap; //true - visible, false - hidden
  103. std::vector<si32> resources;
  104. std::vector<CGHeroInstance *> heroes;
  105. std::vector<CGTownInstance *> towns;
  106. std::vector<CGHeroInstance *> availableHeroes; //heroes available in taverns
  107. std::vector<CGDwelling *> dwellings; //used for town growth
  108. ui8 status; //0 - in game, 1 - loser, 2 - winner <- uses EStatus enum
  109. ui8 daysWithoutCastle;
  110. PlayerState();
  111. //override
  112. void getParents(TCNodes &out, const CBonusSystemNode *root = NULL) const;
  113. void getBonuses(BonusList &out, const CSelector &selector, const CBonusSystemNode *root = NULL) const;
  114. template <typename Handler> void serialize(Handler &h, const int version)
  115. {
  116. h & color & serial & human & currentSelection & fogOfWarMap & resources & status;
  117. h & heroes & towns & availableHeroes & dwellings & bonuses & status & daysWithoutCastle;
  118. h & static_cast<CBonusSystemNode&>(*this);
  119. }
  120. };
  121. struct DLL_EXPORT CObstacleInstance
  122. {
  123. int uniqueID;
  124. int ID; //ID of obstacle (defines type of it)
  125. int pos; //position on battlefield
  126. template <typename Handler> void serialize(Handler &h, const int version)
  127. {
  128. h & ID & pos & uniqueID;
  129. }
  130. };
  131. //only for use in BattleInfo
  132. struct DLL_EXPORT SiegeInfo
  133. {
  134. ui8 wallState[8]; //[0] - keep, [1] - bottom tower, [2] - bottom wall, [3] - below gate, [4] - over gate, [5] - upper wall, [6] - uppert tower, [7] - gate; 1 - intact, 2 - damaged, 3 - destroyed
  135. template <typename Handler> void serialize(Handler &h, const int version)
  136. {
  137. h & wallState;
  138. }
  139. };
  140. struct DLL_EXPORT BattleInfo : public CBonusSystemNode
  141. {
  142. ui8 side1, side2; //side1 - attacker, side2 - defender
  143. si32 round, activeStack;
  144. ui8 siege; // = 0 ordinary battle = 1 a siege with a Fort = 2 a siege with a Citadel = 3 a siege with a Castle
  145. si32 tid; //used during town siege - id of attacked town; -1 if not town defence
  146. int3 tile; //for background and bonuses
  147. CGHeroInstance *heroes[2];
  148. CArmedInstance *belligerents[2]; //may be same as heroes
  149. std::vector<CStack*> stacks;
  150. std::vector<CObstacleInstance> obstacles;
  151. ui8 castSpells[2]; //[0] - attacker, [1] - defender
  152. SiegeInfo si;
  153. template <typename Handler> void serialize(Handler &h, const int version)
  154. {
  155. h & side1 & side2 & round & activeStack & siege & tid & tile & stacks & belligerents & obstacles
  156. & castSpells & si;
  157. h & heroes;
  158. h & static_cast<CBonusSystemNode&>(*this);
  159. }
  160. //////////////////////////////////////////////////////////////////////////
  161. void getBonuses(BonusList &out, const CSelector &selector, const CBonusSystemNode *root = NULL) const;
  162. //////////////////////////////////////////////////////////////////////////
  163. const CStack * getNextStack() const; //which stack will have turn after current one
  164. void getStackQueue(std::vector<const CStack *> &out, int howMany, int turn = 0, int lastMoved = -1) const; //returns stack in order of their movement action
  165. CStack * getStack(int stackID, bool onlyAlive = true);
  166. const CStack * getStack(int stackID, bool onlyAlive = true) const;
  167. CStack * getStackT(int tileID, bool onlyAlive = true);
  168. const CStack * getStackT(int tileID, bool onlyAlive = true) const;
  169. void getAccessibilityMap(bool *accessibility, bool twoHex, bool attackerOwned, bool addOccupiable, std::set<int> & occupyable, bool flying, int stackToOmmit=-1) const; //send pointer to at least 187 allocated bytes
  170. static bool isAccessible(int hex, bool * accessibility, bool twoHex, bool attackerOwned, bool flying, bool lastPos); //helper for makeBFS
  171. void makeBFS(int start, bool*accessibility, int *predecessor, int *dists, bool twoHex, bool attackerOwned, bool flying, bool fillPredecessors) const; //*accessibility must be prepared bool[187] array; last two pointers must point to the at least 187-elements int arrays - there is written result
  172. std::pair< std::vector<int>, int > getPath(int start, int dest, bool*accessibility, bool flyingCreature, bool twoHex, bool attackerOwned); //returned value: pair<path, length>; length may be different than number of elements in path since flying vreatures jump between distant hexes
  173. std::vector<int> getAccessibility(int stackID, bool addOccupiable) const; //returns vector of accessible tiles (taking into account the creature range)
  174. bool isStackBlocked(int ID); //returns true if there is neighboring enemy stack
  175. static signed char mutualPosition(int hex1, int hex2); //returns info about mutual position of given hexes (-1 - they're distant, 0 - left top, 1 - right top, 2 - right, 3 - right bottom, 4 - left bottom, 5 - left)
  176. static std::vector<int> neighbouringTiles(int hex);
  177. ui32 calculateDmg(const CStack* attacker, const CStack* defender, const CGHeroInstance * attackerHero, const CGHeroInstance * defendingHero, bool shooting, ui8 charge, bool lucky); //charge - number of hexes travelled before attack (for champion's jousting)
  178. std::pair<ui32, ui32> calculateDmgRange(const CStack* attacker, const CStack* defender, const CGHeroInstance * attackerHero, const CGHeroInstance * defendingHero, bool shooting, ui8 charge, bool lucky); //charge - number of hexes travelled before attack (for champion's jousting); returns pair <min dmg, max dmg>
  179. void calculateCasualties(std::map<ui32,si32> *casualties) const; //casualties are array of maps size 2 (attacker, defeneder), maps are (crid => amount)
  180. std::set<CStack*> getAttackedCreatures(const CSpell * s, int skillLevel, ui8 attackerOwner, int destinationTile); //calculates stack affected by given spell
  181. static int calculateSpellDuration(const CSpell * spell, const CGHeroInstance * caster, int usedSpellPower);
  182. CStack * generateNewStack(const CStackInstance &base, int stackID, bool attackerOwned, int slot, int /*TerrainTile::EterrainType*/ terrain, int position) const; //helper for CGameHandler::setupBattle and spells addign new stacks to the battlefield
  183. ui32 getSpellCost(const CSpell * sp, const CGHeroInstance * caster) const; //returns cost of given spell
  184. int hexToWallPart(int hex) const; //returns part of destructible wall / gate / keep under given hex or -1 if not found
  185. int lineToWallHex(int line) const; //returns hex with wall in given line
  186. std::pair<const CStack *, int> getNearestStack(const CStack * closest, boost::logic::tribool attackerOwned) const; //if attackerOwned is indetermnate, returened stack is of any owner; hex is the number of hex we should be looking from; returns (nerarest creature, predecessorHex)
  187. ui32 calculateSpellDmg(const CSpell * sp, const CGHeroInstance * caster, const CStack * affectedCreature, int spellSchoolLevel, int usedSpellPower) const; //calculates damage inflicted by spell
  188. si8 hasDistancePenalty(int stackID, int destHex); //determines if given stack has distance penalty shooting given pos
  189. si8 sameSideOfWall(int pos1, int pos2); //determines if given positions are on the same side of wall
  190. si8 hasWallPenalty(int stackID, int destHex); //determines if given stack has wall penalty shooting given pos
  191. si8 canTeleportTo(int stackID, int destHex, int telportLevel); //determines if given stack can teleport to given place
  192. };
  193. class DLL_EXPORT CStack : public CStackInstance
  194. {
  195. public:
  196. ui32 ID; //unique ID of stack
  197. ui32 baseAmount;
  198. ui32 firstHPleft; //HP of first creature in stack
  199. ui8 owner, slot; //owner - player colour (255 for neutrals), slot - position in garrison (may be 255 for neutrals/called creatures)
  200. ui8 attackerOwned; //if true, this stack is owned by attakcer (this one from left hand side of battle)
  201. si16 position; //position on battlefield; -2 - keep, -3 - lower tower, -4 - upper tower
  202. ui8 counterAttacks; //how many counter attacks can be performed more in this turn (by default set at the beginning of the round to 1)
  203. si16 shots; //how many shots left
  204. std::set<ECombatInfo> state;
  205. struct StackEffect
  206. {
  207. ui16 id; //spell id
  208. ui8 level; //skill level
  209. si16 turnsRemain;
  210. template <typename Handler> void serialize(Handler &h, const int version)
  211. {
  212. h & id & level & turnsRemain;
  213. }
  214. };
  215. std::vector<StackEffect> effects;
  216. //overrides
  217. const CCreature* getCreature() const {return type;}
  218. CStack(const CStackInstance *base, int O, int I, bool AO, int S); //c-tor
  219. CStack() : ID(-1), baseAmount(-1), firstHPleft(-1), owner(255), slot(255), attackerOwned(true), position(-1), counterAttacks(1) {} //c-tor
  220. const StackEffect * getEffect(ui16 id, int turn = 0) const; //effect id (SP)
  221. ui8 howManyEffectsSet(ui16 id) const; //returns amount of effects with given id set for this stack
  222. bool willMove(int turn = 0) const; //if stack has remaining move this turn
  223. bool moved(int turn = 0) const; //if stack was already moved this turn
  224. bool canMove(int turn = 0) const; //if stack can move
  225. ui32 Speed(int turn = 0) const; //get speed of creature with all modificators
  226. bool doubleWide() const;
  227. template <typename Handler> void serialize(Handler &h, const int version)
  228. {
  229. h & static_cast<CStackInstance&>(*this);
  230. h & ID & baseAmount & firstHPleft & owner & slot & attackerOwned & position & state & counterAttacks
  231. & shots;
  232. }
  233. bool alive() const //determines if stack is alive
  234. {
  235. return vstd::contains(state,ALIVE);
  236. }
  237. };
  238. class DLL_EXPORT CMP_stack
  239. {
  240. int phase; //rules of which phase will be used
  241. int turn;
  242. public:
  243. bool operator ()(const CStack* a, const CStack* b);
  244. CMP_stack(int Phase = 1, int Turn = 0);
  245. };
  246. struct UpgradeInfo
  247. {
  248. int oldID; //creature to be upgraded
  249. std::vector<int> newID; //possible upgrades
  250. std::vector<std::set<std::pair<int,int> > > cost; // cost[upgrade_serial] -> set of pairs<resource_ID,resource_amount>
  251. UpgradeInfo(){oldID = -1;};
  252. };
  253. struct CPathNode
  254. {
  255. bool accessible; //true if a hero can be on this node
  256. int dist; //distance from the first node of searching; -1 is infinity
  257. CPathNode * theNodeBefore;
  258. int3 coord; //coordiantes
  259. bool visited;
  260. };
  261. struct CGPathNode
  262. {
  263. enum
  264. {
  265. ACCESSIBLE=1, //tile can be entered and passed
  266. VISITABLE, //tile can be entered as the last tile in path
  267. BLOCKVIS, //visitable from neighbouring tile but not passable
  268. BLOCKED, //tile can't be entered nor visited
  269. FLYABLE //if hero flies, he can pass this tile
  270. };
  271. ui8 accessible; //the enum above
  272. ui8 land;
  273. ui8 turns;
  274. ui32 moveRemains;
  275. CGPathNode * theNodeBefore;
  276. int3 coord; //coordinates
  277. CGPathNode();
  278. };
  279. struct DLL_EXPORT CPath
  280. {
  281. std::vector<CPathNode> nodes; //just get node by node
  282. int3 startPos() const; // start point
  283. int3 endPos() const; //destination point
  284. void convert(ui8 mode); //mode=0 -> from 'manifest' to 'object'
  285. };
  286. struct DLL_EXPORT CGPath
  287. {
  288. std::vector<CGPathNode> nodes; //just get node by node
  289. int3 startPos() const; // start point
  290. int3 endPos() const; //destination point
  291. void convert(ui8 mode); //mode=0 -> from 'manifest' to 'object'
  292. };
  293. struct DLL_EXPORT CPathsInfo
  294. {
  295. const CGHeroInstance *hero;
  296. int3 hpos;
  297. int3 sizes;
  298. CGPathNode ***nodes; //[w][h][level]
  299. bool getPath(const int3 &dst, CGPath &out);
  300. CPathsInfo(const int3 &Sizes);
  301. ~CPathsInfo();
  302. };
  303. class DLL_EXPORT CCampaignState
  304. {
  305. public:
  306. CCampaign *camp;
  307. std::string campaignName;
  308. std::vector<ui8> mapsConquered, mapsRemaining;
  309. ui8 currentMap;
  310. void initNewCampaign(const StartInfo &si);
  311. template <typename Handler> void serialize(Handler &h, const int version)
  312. {
  313. h & camp & campaignName & mapsRemaining & mapsConquered & currentMap;
  314. }
  315. };
  316. class DLL_EXPORT CGameState
  317. {
  318. public:
  319. StartInfo* scenarioOps;
  320. CCampaignState *campaign;
  321. ui32 seed;
  322. ui8 currentPlayer; //ID of player currently having turn
  323. BattleInfo *curB; //current battle
  324. ui32 day; //total number of days in game
  325. Mapa * map;
  326. std::map<ui8, PlayerState> players; //ID <-> player state
  327. std::map<int, CGDefInfo*> villages, forts, capitols; //def-info for town graphics
  328. CBonusSystemNode globalEffects;
  329. struct DLL_EXPORT HeroesPool
  330. {
  331. std::map<ui32,CGHeroInstance *> heroesPool; //[subID] - heroes available to buy; NULL if not available
  332. std::map<ui32,ui8> pavailable; // [subid] -> which players can recruit hero (binary flags)
  333. CGHeroInstance * pickHeroFor(bool native, int player, const CTown *town, std::map<ui32,CGHeroInstance *> &available, const CHeroClass *bannedClass = NULL) const;
  334. template <typename Handler> void serialize(Handler &h, const int version)
  335. {
  336. h & heroesPool & pavailable;
  337. }
  338. } hpool; //we have here all heroes available on this map that are not hired
  339. boost::shared_mutex *mx;
  340. PlayerState *getPlayer(ui8 color, bool verbose = true);
  341. const PlayerState *getPlayer(ui8 color, bool verbose = true) const;
  342. void init(StartInfo * si, ui32 checksum, int Seed);
  343. void loadTownDInfos();
  344. void randomizeObject(CGObjectInstance *cur);
  345. std::pair<int,int> pickObject(CGObjectInstance *obj); //chooses type of object to be randomized, returns <type, subtype>
  346. int pickHero(int owner);
  347. void apply(CPack *pack);
  348. CGHeroInstance *getHero(int objid);
  349. CGTownInstance *getTown(int objid);
  350. const CGHeroInstance *getHero(int objid) const;
  351. const CGTownInstance *getTown(int objid) const;
  352. bool battleMoveCreatureStack(int ID, int dest);
  353. bool battleAttackCreatureStack(int ID, int dest);
  354. bool battleShootCreatureStack(int ID, int dest);
  355. bool battleCanFlee(int player); //returns true if player can flee from the battle
  356. int battleGetStack(int pos, bool onlyAlive); //returns ID of stack at given tile
  357. int battleGetBattlefieldType(int3 tile = int3());// 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
  358. const CGHeroInstance * battleGetOwner(int stackID); //returns hero that owns given stack; NULL if none
  359. si8 battleMaxSpellLevel(); //calculates maximum spell level possible to be cast on battlefield - takes into account artifacts of both heroes; if no effects are set, SPELL_LEVELS is returned
  360. bool battleCanShoot(int ID, int dest); //determines if stack with given ID shoot at the selected destination
  361. UpgradeInfo getUpgradeInfo(const CArmedInstance *obj, int stackPos);
  362. //float getMarketEfficiency(int player, int mode=0);
  363. std::set<int> getBuildingRequiments(const CGTownInstance *t, int ID);
  364. int canBuildStructure(const CGTownInstance *t, int ID);// 0 - no more than one capitol, 1 - lack of water, 2 - forbidden, 3 - Add another level to Mage Guild, 4 - already built, 5 - cannot build, 6 - cannot afford, 7 - build, 8 - lack of requirements
  365. bool checkForVisitableDir(const int3 & src, const int3 & dst) const; //check if src tile is visitable from dst tile
  366. bool checkForVisitableDir(const int3 & src, const TerrainTile *pom, const int3 & dst) const; //check if src tile is visitable from dst tile
  367. 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
  368. 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
  369. int3 guardingCreaturePosition (int3 pos) const;
  370. int victoryCheck(ui8 player) const; //checks if given player is winner; -1 if std victory, 1 if special victory, 0 else
  371. int lossCheck(ui8 player) const; //checks if given player is loser; -1 if std loss, 1 if special, 0 else
  372. ui8 checkForStandardWin() const; //returns color of player that accomplished standard victory conditions or 255 if no winner
  373. bool checkForStandardLoss(ui8 player) const; //checks if given player lost the game
  374. void obtainPlayersStats(SThievesGuildInfo & tgi, int level); //fills tgi with info about other players that is available at given level of thieves' guild
  375. std::map<ui32,CGHeroInstance *> unusedHeroesFromPool(); //heroes pool without heroes that are available in taverns
  376. bool isVisible(int3 pos, int player);
  377. bool isVisible(const CGObjectInstance *obj, int player);
  378. CGameState(); //c-tor
  379. ~CGameState(); //d-tor
  380. void getNeighbours(const TerrainTile &srct, int3 tile, std::vector<int3> &vec, const boost::logic::tribool &onLand);
  381. int getMovementCost(const CGHeroInstance *h, const int3 &src, const int3 &dest, int remainingMovePoints=-1, bool checkLast=true);
  382. 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
  383. template <typename Handler> void serialize(Handler &h, const int version)
  384. {
  385. h & scenarioOps & seed & currentPlayer & day & map & players & hpool & globalEffects & campaign;
  386. if(!h.saving)
  387. {
  388. loadTownDInfos();
  389. }
  390. }
  391. friend class CCallback;
  392. friend class CLuaCallback;
  393. friend class CClient;
  394. friend void initGameState(Mapa * map, CGameInfo * cgi);
  395. friend class IGameCallback;
  396. friend class CMapHandler;
  397. friend class CGameHandler;
  398. };
  399. #endif // __CGAMESTATE_H__