1. Summary
  2. Files
  3. Support
  4. Report Spam
  5. Create account
  6. Log in

root/branches/programmingChallenge/lib/CGameState.h @ 2675

Revision 2675, 15.6 KB (checked in by mateuszb, 12 months ago)

[programming challenge, SSN] today's changes

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