CGameState.h 20 KB

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