CGameState.h 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  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. // typedef si32 TResourceUnit;
  83. // typedef std::vector<si32> TResourceVector;
  84. // typedef std::set<si32> TResourceSet;
  85. struct DLL_EXPORT SThievesGuildInfo
  86. {
  87. std::vector<ui8> playerColors; //colors of players that are in-game
  88. std::vector< std::list< ui8 > > numOfTowns, numOfHeroes, gold, woodOre, mercSulfCrystGems, obelisks, artifacts, army, income; // [place] -> [colours of players]
  89. std::map<ui8, InfoAboutHero> colorToBestHero; //maps player's color to his best heros'
  90. std::map<ui8, si8> personality; // color to personality // -1 - human, AI -> (00 - random, 01 - warrior, 02 - builder, 03 - explorer)
  91. std::map<ui8, si32> bestCreature; // color to ID // id or -1 if not known
  92. // template <typename Handler> void serialize(Handler &h, const int version)
  93. // {
  94. // h & playerColors & numOfTowns & numOfHeroes & gold & woodOre & mercSulfCrystGems & obelisks & artifacts & army & income;
  95. // h & colorToBestHero & personality & bestCreature;
  96. // }
  97. };
  98. struct DLL_EXPORT PlayerState : public CBonusSystemNode
  99. {
  100. public:
  101. enum EStatus {INGAME, LOSER, WINNER};
  102. ui8 color, serial;
  103. ui8 human; //true if human controlled player, false for AI
  104. ui32 currentSelection; //id of hero/town, 0xffffffff if none
  105. std::vector<std::vector<std::vector<ui8> > > fogOfWarMap; //true - visible, false - hidden
  106. std::vector<si32> resources;
  107. std::vector<CGHeroInstance *> heroes;
  108. std::vector<CGTownInstance *> towns;
  109. std::vector<CGHeroInstance *> availableHeroes; //heroes available in taverns
  110. std::vector<CGDwelling *> dwellings; //used for town growth
  111. ui8 status; //0 - in game, 1 - loser, 2 - winner <- uses EStatus enum
  112. ui8 daysWithoutCastle;
  113. PlayerState();
  114. //override
  115. void getParents(TCNodes &out, const CBonusSystemNode *root = NULL) const;
  116. void getBonuses(BonusList &out, const CSelector &selector, const CBonusSystemNode *root = NULL) const;
  117. template <typename Handler> void serialize(Handler &h, const int version)
  118. {
  119. h & color & serial & human & currentSelection & fogOfWarMap & resources & status;
  120. h & heroes & towns & availableHeroes & dwellings & bonuses & status & daysWithoutCastle;
  121. h & static_cast<CBonusSystemNode&>(*this);
  122. }
  123. };
  124. struct DLL_EXPORT CObstacleInstance
  125. {
  126. int uniqueID;
  127. int ID; //ID of obstacle (defines type of it)
  128. int pos; //position on battlefield
  129. template <typename Handler> void serialize(Handler &h, const int version)
  130. {
  131. h & ID & pos & uniqueID;
  132. }
  133. };
  134. //only for use in BattleInfo
  135. struct DLL_EXPORT SiegeInfo
  136. {
  137. 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
  138. template <typename Handler> void serialize(Handler &h, const int version)
  139. {
  140. h & wallState;
  141. }
  142. };
  143. struct DLL_EXPORT BattleInfo : public CBonusSystemNode
  144. {
  145. ui8 side1, side2; //side1 - attacker, side2 - defender
  146. si32 round, activeStack;
  147. ui8 siege; // = 0 ordinary battle = 1 a siege with a Fort = 2 a siege with a Citadel = 3 a siege with a Castle
  148. si32 tid; //used during town siege - id of attacked town; -1 if not town defence
  149. int3 tile; //for background and bonuses
  150. CGHeroInstance *heroes[2];
  151. CArmedInstance *belligerents[2]; //may be same as heroes
  152. std::vector<CStack*> stacks;
  153. std::vector<CObstacleInstance> obstacles;
  154. ui8 castSpells[2]; //[0] - attacker, [1] - defender
  155. SiegeInfo si;
  156. template <typename Handler> void serialize(Handler &h, const int version)
  157. {
  158. h & side1 & side2 & round & activeStack & siege & tid & tile & stacks & belligerents & obstacles
  159. & castSpells & si;
  160. h & heroes;
  161. h & static_cast<CBonusSystemNode&>(*this);
  162. }
  163. //////////////////////////////////////////////////////////////////////////
  164. void getBonuses(BonusList &out, const CSelector &selector, const CBonusSystemNode *root = NULL) const;
  165. //////////////////////////////////////////////////////////////////////////
  166. const CStack * getNextStack() const; //which stack will have turn after current one
  167. void getStackQueue(std::vector<const CStack *> &out, int howMany, int turn = 0, int lastMoved = -1) const; //returns stack in order of their movement action
  168. CStack * getStack(int stackID, bool onlyAlive = true);
  169. const CStack * getStack(int stackID, bool onlyAlive = true) const;
  170. CStack * getStackT(int tileID, bool onlyAlive = true);
  171. const CStack * getStackT(int tileID, bool onlyAlive = true) const;
  172. 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
  173. static bool isAccessible(int hex, bool * accessibility, bool twoHex, bool attackerOwned, bool flying, bool lastPos); //helper for makeBFS
  174. 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
  175. 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
  176. std::vector<int> getAccessibility(int stackID, bool addOccupiable) const; //returns vector of accessible tiles (taking into account the creature range)
  177. bool isStackBlocked(int ID); //returns true if there is neighboring enemy stack
  178. 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)
  179. static std::vector<int> neighbouringTiles(int hex);
  180. 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)
  181. 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>
  182. void calculateCasualties(std::map<ui32,si32> *casualties) const; //casualties are array of maps size 2 (attacker, defeneder), maps are (crid => amount)
  183. std::set<CStack*> getAttackedCreatures(const CSpell * s, int skillLevel, ui8 attackerOwner, int destinationTile); //calculates stack affected by given spell
  184. static int calculateSpellDuration(const CSpell * spell, const CGHeroInstance * caster, int usedSpellPower);
  185. 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
  186. ui32 getSpellCost(const CSpell * sp, const CGHeroInstance * caster) const; //returns cost of given spell
  187. int hexToWallPart(int hex) const; //returns part of destructible wall / gate / keep under given hex or -1 if not found
  188. int lineToWallHex(int line) const; //returns hex with wall in given line
  189. 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)
  190. ui32 calculateSpellDmg(const CSpell * sp, const CGHeroInstance * caster, const CStack * affectedCreature, int spellSchoolLevel, int usedSpellPower) const; //calculates damage inflicted by spell
  191. si8 hasDistancePenalty(int stackID, int destHex); //determines if given stack has distance penalty shooting given pos
  192. si8 sameSideOfWall(int pos1, int pos2); //determines if given positions are on the same side of wall
  193. si8 hasWallPenalty(int stackID, int destHex); //determines if given stack has wall penalty shooting given pos
  194. si8 canTeleportTo(int stackID, int destHex, int telportLevel); //determines if given stack can teleport to given place
  195. };
  196. class DLL_EXPORT CStack : public CStackInstance
  197. {
  198. public:
  199. ui32 ID; //unique ID of stack
  200. ui32 baseAmount;
  201. ui32 firstHPleft; //HP of first creature in stack
  202. ui8 owner, slot; //owner - player colour (255 for neutrals), slot - position in garrison (may be 255 for neutrals/called creatures)
  203. ui8 attackerOwned; //if true, this stack is owned by attakcer (this one from left hand side of battle)
  204. si16 position; //position on battlefield; -2 - keep, -3 - lower tower, -4 - upper tower
  205. ui8 counterAttacks; //how many counter attacks can be performed more in this turn (by default set at the beginning of the round to 1)
  206. si16 shots; //how many shots left
  207. std::set<ECombatInfo> state;
  208. struct StackEffect
  209. {
  210. ui16 id; //spell id
  211. ui8 level; //skill level
  212. si16 turnsRemain;
  213. template <typename Handler> void serialize(Handler &h, const int version)
  214. {
  215. h & id & level & turnsRemain;
  216. }
  217. };
  218. std::vector<StackEffect> effects;
  219. //overrides
  220. const CCreature* getCreature() const {return type;}
  221. CStack(const CStackInstance *base, int O, int I, bool AO, int S); //c-tor
  222. CStack() : ID(-1), baseAmount(-1), firstHPleft(-1), owner(255), slot(255), attackerOwned(true), position(-1), counterAttacks(1) {} //c-tor
  223. const StackEffect * getEffect(ui16 id, int turn = 0) const; //effect id (SP)
  224. ui8 howManyEffectsSet(ui16 id) const; //returns amount of effects with given id set for this stack
  225. bool willMove(int turn = 0) const; //if stack has remaining move this turn
  226. bool moved(int turn = 0) const; //if stack was already moved this turn
  227. bool canMove(int turn = 0) const; //if stack can move
  228. ui32 Speed(int turn = 0) const; //get speed of creature with all modificators
  229. bool doubleWide() const;
  230. int occupiedHex() const; //returns number of occupied hex (not the position) if stack is double wide; otherwise -1
  231. template <typename Handler> void serialize(Handler &h, const int version)
  232. {
  233. h & static_cast<CStackInstance&>(*this);
  234. h & ID & baseAmount & firstHPleft & owner & slot & attackerOwned & position & state & counterAttacks
  235. & shots;
  236. }
  237. bool alive() const //determines if stack is alive
  238. {
  239. return vstd::contains(state,ALIVE);
  240. }
  241. };
  242. class DLL_EXPORT CMP_stack
  243. {
  244. int phase; //rules of which phase will be used
  245. int turn;
  246. public:
  247. bool operator ()(const CStack* a, const CStack* b);
  248. CMP_stack(int Phase = 1, int Turn = 0);
  249. };
  250. struct UpgradeInfo
  251. {
  252. int oldID; //creature to be upgraded
  253. std::vector<int> newID; //possible upgrades
  254. std::vector<std::set<std::pair<int,int> > > cost; // cost[upgrade_serial] -> set of pairs<resource_ID,resource_amount>
  255. UpgradeInfo(){oldID = -1;};
  256. };
  257. struct CPathNode
  258. {
  259. bool accessible; //true if a hero can be on this node
  260. int dist; //distance from the first node of searching; -1 is infinity
  261. CPathNode * theNodeBefore;
  262. int3 coord; //coordiantes
  263. bool visited;
  264. };
  265. struct CGPathNode
  266. {
  267. enum
  268. {
  269. ACCESSIBLE=1, //tile can be entered and passed
  270. VISITABLE, //tile can be entered as the last tile in path
  271. BLOCKVIS, //visitable from neighbouring tile but not passable
  272. BLOCKED, //tile can't be entered nor visited
  273. FLYABLE //if hero flies, he can pass this tile
  274. };
  275. ui8 accessible; //the enum above
  276. ui8 land;
  277. ui8 turns;
  278. ui32 moveRemains;
  279. CGPathNode * theNodeBefore;
  280. int3 coord; //coordinates
  281. CGPathNode();
  282. };
  283. struct DLL_EXPORT CPath
  284. {
  285. std::vector<CPathNode> nodes; //just get node by node
  286. int3 startPos() const; // start point
  287. int3 endPos() const; //destination point
  288. void convert(ui8 mode); //mode=0 -> from 'manifest' to 'object'
  289. };
  290. struct DLL_EXPORT CGPath
  291. {
  292. std::vector<CGPathNode> nodes; //just get node by node
  293. int3 startPos() const; // start point
  294. int3 endPos() const; //destination point
  295. void convert(ui8 mode); //mode=0 -> from 'manifest' to 'object'
  296. };
  297. struct DLL_EXPORT CPathsInfo
  298. {
  299. const CGHeroInstance *hero;
  300. int3 hpos;
  301. int3 sizes;
  302. CGPathNode ***nodes; //[w][h][level]
  303. bool getPath(const int3 &dst, CGPath &out);
  304. CPathsInfo(const int3 &Sizes);
  305. ~CPathsInfo();
  306. };
  307. class DLL_EXPORT CCampaignState
  308. {
  309. public:
  310. CCampaign *camp;
  311. std::string campaignName;
  312. std::vector<ui8> mapsConquered, mapsRemaining;
  313. ui8 currentMap;
  314. void initNewCampaign(const StartInfo &si);
  315. template <typename Handler> void serialize(Handler &h, const int version)
  316. {
  317. h & camp & campaignName & mapsRemaining & mapsConquered & currentMap;
  318. }
  319. };
  320. class DLL_EXPORT CGameState
  321. {
  322. public:
  323. StartInfo* scenarioOps;
  324. CCampaignState *campaign;
  325. ui32 seed;
  326. ui8 currentPlayer; //ID of player currently having turn
  327. BattleInfo *curB; //current battle
  328. ui32 day; //total number of days in game
  329. Mapa * map;
  330. std::map<ui8, PlayerState> players; //ID <-> player state
  331. std::map<int, CGDefInfo*> villages, forts, capitols; //def-info for town graphics
  332. CBonusSystemNode globalEffects;
  333. struct DLL_EXPORT HeroesPool
  334. {
  335. std::map<ui32,CGHeroInstance *> heroesPool; //[subID] - heroes available to buy; NULL if not available
  336. std::map<ui32,ui8> pavailable; // [subid] -> which players can recruit hero (binary flags)
  337. CGHeroInstance * pickHeroFor(bool native, int player, const CTown *town, std::map<ui32,CGHeroInstance *> &available, const CHeroClass *bannedClass = NULL) const;
  338. template <typename Handler> void serialize(Handler &h, const int version)
  339. {
  340. h & heroesPool & pavailable;
  341. }
  342. } hpool; //we have here all heroes available on this map that are not hired
  343. boost::shared_mutex *mx;
  344. PlayerState *getPlayer(ui8 color, bool verbose = true);
  345. const PlayerState *getPlayer(ui8 color, bool verbose = true) const;
  346. void init(StartInfo * si, ui32 checksum, int Seed);
  347. void loadTownDInfos();
  348. void randomizeObject(CGObjectInstance *cur);
  349. std::pair<int,int> pickObject(CGObjectInstance *obj); //chooses type of object to be randomized, returns <type, subtype>
  350. int pickHero(int owner);
  351. void apply(CPack *pack);
  352. CGHeroInstance *getHero(int objid);
  353. CGTownInstance *getTown(int objid);
  354. const CGHeroInstance *getHero(int objid) const;
  355. const CGTownInstance *getTown(int objid) const;
  356. bool battleMoveCreatureStack(int ID, int dest);
  357. bool battleAttackCreatureStack(int ID, int dest);
  358. bool battleShootCreatureStack(int ID, int dest);
  359. bool battleCanFlee(int player); //returns true if player can flee from the battle
  360. int battleGetStack(int pos, bool onlyAlive); //returns ID of stack at given tile
  361. 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
  362. const CGHeroInstance * battleGetOwner(int stackID); //returns hero that owns given stack; NULL if none
  363. 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
  364. bool battleCanShoot(int ID, int dest); //determines if stack with given ID shoot at the selected destination
  365. UpgradeInfo getUpgradeInfo(const CStackInstance &stack);
  366. //float getMarketEfficiency(int player, int mode=0);
  367. std::set<int> getBuildingRequiments(const CGTownInstance *t, int ID);
  368. 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
  369. bool checkForVisitableDir(const int3 & src, const int3 & dst) const; //check if src tile is visitable from dst tile
  370. bool checkForVisitableDir(const int3 & src, const TerrainTile *pom, const int3 & dst) const; //check if src tile is visitable from dst tile
  371. 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
  372. 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
  373. int3 guardingCreaturePosition (int3 pos) const;
  374. int victoryCheck(ui8 player) const; //checks if given player is winner; -1 if std victory, 1 if special victory, 0 else
  375. int lossCheck(ui8 player) const; //checks if given player is loser; -1 if std loss, 1 if special, 0 else
  376. ui8 checkForStandardWin() const; //returns color of player that accomplished standard victory conditions or 255 if no winner
  377. bool checkForStandardLoss(ui8 player) const; //checks if given player lost the game
  378. void obtainPlayersStats(SThievesGuildInfo & tgi, int level); //fills tgi with info about other players that is available at given level of thieves' guild
  379. std::map<ui32,CGHeroInstance *> unusedHeroesFromPool(); //heroes pool without heroes that are available in taverns
  380. bool isVisible(int3 pos, int player);
  381. bool isVisible(const CGObjectInstance *obj, int player);
  382. CGameState(); //c-tor
  383. ~CGameState(); //d-tor
  384. void getNeighbours(const TerrainTile &srct, int3 tile, std::vector<int3> &vec, const boost::logic::tribool &onLand, bool limitCoastSailing);
  385. int getMovementCost(const CGHeroInstance *h, const int3 &src, const int3 &dest, int remainingMovePoints=-1, bool checkLast=true);
  386. 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
  387. template <typename Handler> void serialize(Handler &h, const int version)
  388. {
  389. h & scenarioOps & seed & currentPlayer & day & map & players & hpool & globalEffects & campaign;
  390. if(!h.saving)
  391. {
  392. loadTownDInfos();
  393. }
  394. }
  395. friend class CCallback;
  396. friend class CLuaCallback;
  397. friend class CClient;
  398. friend void initGameState(Mapa * map, CGameInfo * cgi);
  399. friend class IGameCallback;
  400. friend class CMapHandler;
  401. friend class CGameHandler;
  402. };
  403. #endif // __CGAMESTATE_H__