CGameState.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408
  1. #ifndef __CGAMESTATE_H__
  2. #define __CGAMESTATE_H__
  3. #include "../global.h"
  4. #ifndef _MSC_VER
  5. #include "../hch/CCreatureHandler.h"
  6. #include "VCMI_Lib.h"
  7. #include "map.h"
  8. #endif
  9. #include <set>
  10. #include <vector>
  11. #include "StackFeature.h"
  12. #ifdef _WIN32
  13. #include <tchar.h>
  14. #else
  15. #include "../tchar_amigaos4.h"
  16. #endif
  17. /*
  18. * CGameState.h, part of VCMI engine
  19. *
  20. * Authors: listed in file AUTHORS in main folder
  21. *
  22. * License: GNU General Public License v2.0 or later
  23. * Full text of license available in license.txt file, in main folder
  24. *
  25. */
  26. class CTown;
  27. class CScriptCallback;
  28. class CCallback;
  29. class CLuaCallback;
  30. class CCPPObjectScript;
  31. class CCreatureSet;
  32. class CStack;
  33. class CGHeroInstance;
  34. class CGTownInstance;
  35. class CArmedInstance;
  36. class CGDwelling;
  37. class CGDefInfo;
  38. class CObjectScript;
  39. class CGObjectInstance;
  40. class CCreature;
  41. struct Mapa;
  42. struct StartInfo;
  43. struct SDL_Surface;
  44. class CMapHandler;
  45. class CPathfinder;
  46. struct SetObjectProperty;
  47. struct MetaString;
  48. struct CPack;
  49. class CSpell;
  50. struct TerrainTile;
  51. namespace boost
  52. {
  53. class shared_mutex;
  54. }
  55. struct DLL_EXPORT PlayerState
  56. {
  57. public:
  58. ui8 color, serial;
  59. ui8 human; //true if human controlled player, false for AI
  60. ui32 currentSelection; //id of hero/town, 0xffffffff if none
  61. std::vector<std::vector<std::vector<ui8> > > fogOfWarMap; //true - visible, false - hidden
  62. std::vector<si32> resources;
  63. std::vector<CGHeroInstance *> heroes;
  64. std::vector<CGTownInstance *> towns;
  65. std::vector<CGHeroInstance *> availableHeroes; //heroes available in taverns
  66. std::vector<CGDwelling *> dwellings; //used for town growth
  67. PlayerState();
  68. template <typename Handler> void serialize(Handler &h, const int version)
  69. {
  70. h & color & serial & human & currentSelection & fogOfWarMap & resources;
  71. ui32 size;
  72. if(h.saving) //write subids of available heroes
  73. {
  74. size = availableHeroes.size();
  75. h & size;
  76. for(size_t i=0; i < size; i++)
  77. h & availableHeroes[i]->subID;
  78. }
  79. else
  80. {
  81. ui32 hid;
  82. h & size;
  83. for(size_t i=0; i < size; i++)
  84. {
  85. //fill availableHeroes with dummy hero instances, holding subids
  86. h & hid;
  87. availableHeroes.push_back(new CGHeroInstance);
  88. availableHeroes[availableHeroes.size()-1]->subID = hid;
  89. }
  90. }
  91. }
  92. };
  93. struct DLL_EXPORT CObstacleInstance
  94. {
  95. int uniqueID;
  96. int ID; //ID of obstacle (defines type of it)
  97. int pos; //position on battlefield
  98. template <typename Handler> void serialize(Handler &h, const int version)
  99. {
  100. h & ID & pos & uniqueID;
  101. }
  102. };
  103. //only for use in BattleInfo
  104. struct DLL_EXPORT SiegeInfo
  105. {
  106. 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
  107. template <typename Handler> void serialize(Handler &h, const int version)
  108. {
  109. h & wallState;
  110. }
  111. };
  112. struct DLL_EXPORT BattleInfo
  113. {
  114. ui8 side1, side2; //side1 - attacker, side2 - defender
  115. si32 round, activeStack;
  116. ui8 siege; // = 0 ordinary battle = 1 a siege with a Fort = 2 a siege with a Citadel = 3 a siege with a Castle
  117. si32 tid; //used during town siege - id of attacked town; -1 if not town defence
  118. int3 tile; //for background and bonuses
  119. CGHeroInstance *heroes[2];
  120. CCreatureSet army1, army2;
  121. std::vector<CStack*> stacks;
  122. std::vector<CObstacleInstance> obstacles;
  123. ui8 castSpells[2]; //[0] - attacker, [1] - defender
  124. SiegeInfo si;
  125. template <typename Handler> void serialize(Handler &h, const int version)
  126. {
  127. h & side1 & side2 & round & activeStack & siege & tid & tile & stacks & army1 & army2 & obstacles
  128. & castSpells & si;
  129. h & heroes;
  130. }
  131. const CStack * getNextStack() const; //which stack will have turn after current one
  132. void getStackQueue(std::vector<const CStack *> &out, int howMany, int turn = 0, int lastMoved = -1) const; //returns stack in order of their movement action
  133. CStack * getStack(int stackID, bool onlyAlive = true);
  134. const CStack * getStack(int stackID, bool onlyAlive = true) const;
  135. CStack * getStackT(int tileID, bool onlyAlive = true);
  136. const CStack * getStackT(int tileID, bool onlyAlive = true) const;
  137. 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
  138. static bool isAccessible(int hex, bool * accessibility, bool twoHex, bool attackerOwned, bool flying, bool lastPos); //helper for makeBFS
  139. 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
  140. 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
  141. std::vector<int> getAccessibility(int stackID, bool addOccupiable) const; //returns vector of accessible tiles (taking into account the creature range)
  142. bool isStackBlocked(int ID); //returns true if there is neighbouring enemy stack
  143. 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)
  144. static std::vector<int> neighbouringTiles(int hex);
  145. static ui32 calculateDmg(const CStack* attacker, const CStack* defender, const CGHeroInstance * attackerHero, const CGHeroInstance * defendingHero, bool shooting, ui8 charge); //charge - number of hexes travelled before attack (for champion's jousting)
  146. static std::pair<ui32, ui32> calculateDmgRange(const CStack* attacker, const CStack* defender, const CGHeroInstance * attackerHero, const CGHeroInstance * defendingHero, bool shooting, ui8 charge); //charge - number of hexes travelled before attack (for champion's jousting); returns pair <min dmg, max dmg>
  147. void calculateCasualties(std::map<ui32,si32> *casualties) const; //casualties are array of maps size 2 (attacker, defeneder), maps are (crid => amount)
  148. std::set<CStack*> getAttackedCreatures(const CSpell * s, const CGHeroInstance * caster, int destinationTile); //calculates stack affected by given spell
  149. static int calculateSpellDuration(const CSpell * spell, const CGHeroInstance * caster);
  150. CStack * generateNewStack(const CGHeroInstance * owner, int creatureID, int amount, 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
  151. ui32 getSpellCost(const CSpell * sp, const CGHeroInstance * caster) const; //returns cost of given spell
  152. int hexToWallPart(int hex) const; //returns part of destructible wall / gate / keep under given hex or -1 if not found
  153. 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)
  154. };
  155. class DLL_EXPORT CStack
  156. {
  157. public:
  158. ui32 ID; //unique ID of stack
  159. CCreature * creature;
  160. ui32 amount, baseAmount;
  161. ui32 firstHPleft; //HP of first creature in stack
  162. ui8 owner, slot; //owner - player colour (255 for neutrals), slot - position in garrison (may be 255 for neutrals/called creatures)
  163. ui8 attackerOwned; //if true, this stack is owned by attakcer (this one from left hand side of battle)
  164. si16 position; //position on battlefield; -2 - keep, -3 - lower tower, -4 - upper tower
  165. ui8 counterAttacks; //how many counter attacks can be performed more in this turn (by default set at the beginning of the round to 1)
  166. si16 shots; //how many shots left
  167. si8 morale, luck; //base stack luck/morale
  168. std::vector<StackFeature> features;
  169. std::set<ECombatInfo> state;
  170. struct StackEffect
  171. {
  172. ui16 id; //spell id
  173. ui8 level; //skill level
  174. ui16 turnsRemain;
  175. template <typename Handler> void serialize(Handler &h, const int version)
  176. {
  177. h & id & level & turnsRemain;
  178. }
  179. };
  180. std::vector<StackEffect> effects;
  181. int valOfFeatures(StackFeature::ECombatFeatures type, int subtype = -1024, int turn = 0) const;//subtype -> subtype of bonus, if -1024 then any
  182. bool hasFeatureOfType(StackFeature::ECombatFeatures type, int subtype = -1024, int turn = 0) const; //determines if stack has a bonus of given type (and optionally subtype)
  183. CStack(CCreature * C, int A, int O, int I, bool AO, int S); //c-tor
  184. CStack() : ID(-1), creature(NULL), amount(-1), baseAmount(-1), firstHPleft(-1), owner(255), slot(255), attackerOwned(true), position(-1), counterAttacks(1) {} //c-tor
  185. const StackEffect * getEffect(ui16 id, int turn = 0) const; //effect id (SP)
  186. ui8 howManyEffectsSet(ui16 id) const; //returns amount of effects with given id set for this stack
  187. bool willMove(int turn = 0) const; //if stack has remaining move this turn
  188. bool moved(int turn = 0) const; //if stack was already moved this turn
  189. bool canMove(int turn = 0) const; //if stack can move
  190. ui32 Speed(int turn = 0) const; //get speed of creature with all modificators
  191. si8 Morale() const; //get morale of stack with all modificators
  192. si8 Luck() const; //get luck of stack with all modificators
  193. si32 Attack() const; //get attack of stack with all modificators
  194. si32 Defense(bool withFrenzy = true) const; //get defense of stack with all modificators
  195. ui16 MaxHealth() const; //get max HP of stack with all modifiers
  196. template <typename Handler> void save(Handler &h, const int version)
  197. {
  198. h & creature->idNumber;
  199. }
  200. template <typename Handler> void load(Handler &h, const int version)
  201. {
  202. ui32 id;
  203. h & id;
  204. creature = &VLC->creh->creatures[id];
  205. //features = creature->abilities;
  206. }
  207. template <typename Handler> void serialize(Handler &h, const int version)
  208. {
  209. h & ID & amount & baseAmount & firstHPleft & owner & slot & attackerOwned & position & state & counterAttacks
  210. & shots & morale & luck & features;
  211. if(h.saving)
  212. save(h,version);
  213. else
  214. load(h,version);
  215. }
  216. bool alive() const //determines if stack is alive
  217. {
  218. return vstd::contains(state,ALIVE);
  219. }
  220. };
  221. class DLL_EXPORT CMP_stack
  222. {
  223. int phase; //rules of which phase will be used
  224. int turn;
  225. public:
  226. bool operator ()(const CStack* a, const CStack* b);
  227. CMP_stack(int Phase = 1, int Turn = 0);
  228. };
  229. struct UpgradeInfo
  230. {
  231. int oldID; //creature to be upgraded
  232. std::vector<int> newID; //possible upgrades
  233. std::vector<std::set<std::pair<int,int> > > cost; // cost[upgrade_serial] -> set of pairs<resource_ID,resource_amount>
  234. UpgradeInfo(){oldID = -1;};
  235. };
  236. struct CPathNode
  237. {
  238. bool accessible; //true if a hero can be on this node
  239. int dist; //distance from the first node of searching; -1 is infinity
  240. CPathNode * theNodeBefore;
  241. int3 coord; //coordiantes
  242. bool visited;
  243. };
  244. struct CGPathNode
  245. {
  246. enum {ACCESSIBLE=1, VISITABLE, BLOCKVIS, BLOCKED}; //BLOCKVIS - visitable from neighbouring tile but not passable
  247. ui8 accessible; //the enum above
  248. ui8 land;
  249. ui8 turns;
  250. ui32 moveRemains;
  251. CGPathNode * theNodeBefore;
  252. int3 coord; //coordinates
  253. CGPathNode();
  254. };
  255. struct DLL_EXPORT CPath
  256. {
  257. std::vector<CPathNode> nodes; //just get node by node
  258. int3 startPos() const; // start point
  259. int3 endPos() const; //destination point
  260. void convert(ui8 mode); //mode=0 -> from 'manifest' to 'object'
  261. };
  262. struct DLL_EXPORT CGPath
  263. {
  264. std::vector<CGPathNode> nodes; //just get node by node
  265. int3 startPos() const; // start point
  266. int3 endPos() const; //destination point
  267. void convert(ui8 mode); //mode=0 -> from 'manifest' to 'object'
  268. };
  269. struct DLL_EXPORT CPathsInfo
  270. {
  271. const CGHeroInstance *hero;
  272. int3 hpos;
  273. int3 sizes;
  274. CGPathNode ***nodes; //[w][h][level]
  275. bool getPath(const int3 &dst, CGPath &out);
  276. CPathsInfo(const int3 &Sizes);
  277. ~CPathsInfo();
  278. };
  279. class DLL_EXPORT CGameState
  280. {
  281. public:
  282. StartInfo* scenarioOps;
  283. ui32 seed;
  284. ui8 currentPlayer; //ID of player currently having turn
  285. BattleInfo *curB; //current battle
  286. ui32 day; //total number of days in game
  287. Mapa * map;
  288. std::map<ui8,PlayerState> players; //ID <-> player state
  289. std::map<int, CGDefInfo*> villages, forts, capitols; //def-info for town graphics
  290. std::vector<ui32> resVals; //default values of resources in gold
  291. struct DLL_EXPORT HeroesPool
  292. {
  293. std::map<ui32,CGHeroInstance *> heroesPool; //[subID] - heroes available to buy; NULL if not available
  294. std::map<ui32,ui8> pavailable; // [subid] -> which players can recruit hero
  295. CGHeroInstance * pickHeroFor(bool native, int player, const CTown *town, std::map<ui32,CGHeroInstance *> &available) const;
  296. template <typename Handler> void serialize(Handler &h, const int version)
  297. {
  298. h & heroesPool & pavailable;
  299. }
  300. } hpool; //we have here all heroes available on this map that are not hired
  301. boost::shared_mutex *mx;
  302. PlayerState *getPlayer(ui8 color);
  303. void init(StartInfo * si, Mapa * map, int Seed);
  304. void loadTownDInfos();
  305. void randomizeObject(CGObjectInstance *cur);
  306. std::pair<int,int> pickObject(CGObjectInstance *obj); //chooses type of object to be randomized, returns <type, subtype>
  307. int pickHero(int owner);
  308. void apply(CPack *pack);
  309. CGHeroInstance *getHero(int objid);
  310. CGTownInstance *getTown(int objid);
  311. bool battleMoveCreatureStack(int ID, int dest);
  312. bool battleAttackCreatureStack(int ID, int dest);
  313. bool battleShootCreatureStack(int ID, int dest);
  314. bool battleCanFlee(int player); //returns true if player can flee from the battle
  315. int battleGetStack(int pos, bool onlyAlive); //returns ID of stack at given tile
  316. 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
  317. const CGHeroInstance * battleGetOwner(int stackID); //returns hero that owns given stack; NULL if none
  318. 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
  319. bool battleCanShoot(int ID, int dest); //determines if stack with given ID shoot at the selected destination
  320. UpgradeInfo getUpgradeInfo(const CArmedInstance *obj, int stackPos);
  321. float getMarketEfficiency(int player, int mode=0);
  322. 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
  323. bool checkForVisitableDir(const int3 & src, const int3 & dst) const; //check if src tile is visitable from dst tile
  324. bool checkForVisitableDir(const int3 & src, const TerrainTile *pom, const int3 & dst) const; //check if src tile is visitable from dst tile
  325. 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
  326. 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
  327. bool isVisible(int3 pos, int player);
  328. bool isVisible(const CGObjectInstance *obj, int player);
  329. CGameState(); //c-tor
  330. ~CGameState(); //d-tor
  331. void getNeighbours(const TerrainTile &srct, int3 tile, std::vector<int3> &vec, const boost::logic::tribool &onLand);
  332. int getMovementCost(const CGHeroInstance *h, const int3 &src, const int3 &dest, int remainingMovePoints=-1, bool checkLast=true);
  333. 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
  334. template <typename Handler> void serialize(Handler &h, const int version)
  335. {
  336. h & scenarioOps & seed & currentPlayer & day & map & players & resVals & hpool;
  337. if(!h.saving)
  338. {
  339. loadTownDInfos();
  340. //recreating towns/heroes vectors in players entries
  341. for(int i=0; i<map->towns.size(); i++)
  342. if(map->towns[i]->tempOwner < PLAYER_LIMIT)
  343. getPlayer(map->towns[i]->tempOwner)->towns.push_back(map->towns[i]);
  344. for(int i=0; i<map->heroes.size(); i++)
  345. if(map->heroes[i]->tempOwner < PLAYER_LIMIT)
  346. getPlayer(map->heroes[i]->tempOwner)->heroes.push_back(map->heroes[i]);
  347. //recreating available heroes
  348. for(std::map<ui8,PlayerState>::iterator i=players.begin(); i!=players.end(); i++)
  349. {
  350. for(size_t j=0; j < i->second.availableHeroes.size(); j++)
  351. {
  352. ui32 hlp = i->second.availableHeroes[j]->subID;
  353. delete i->second.availableHeroes[j];
  354. i->second.availableHeroes[j] = hpool.heroesPool[hlp];
  355. }
  356. }
  357. }
  358. }
  359. friend class CCallback;
  360. friend class CLuaCallback;
  361. friend class CClient;
  362. friend void initGameState(Mapa * map, CGameInfo * cgi);
  363. friend class IGameCallback;
  364. friend class CMapHandler;
  365. friend class CGameHandler;
  366. };
  367. #endif // __CGAMESTATE_H__